完善续期通知与前端界面

This commit is contained in:
Christ committed 2026-07-10 10:38:25 +08:00
1 parent 25419c027f
commit 45f895d0c4
64 files changed
+2948 -487

No files matched your search

+45 -13
View File
@@ -8,7 +8,7 @@ import ItemList from './components/ItemList';
import Settings from './components/Settings';
import Rules from './components/Rules';
import Notifications from './components/Notifications';
import { login, verifySession } from './services/api';
import { login, logout, verifySession } from './services/api';
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
interface DeliveryRuleTarget {
@@ -40,6 +40,7 @@ const isWindows = /Win/i.test(navigator.platform || navigator.userAgent);
const App: React.FC = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isAdmin, setIsAdmin] = useState(false);
const [activeTab, setActiveTab] = useState(tabFromPath);
const [checkingAuth, setCheckingAuth] = useState(true);
const [needsInit, setNeedsInit] = useState(false);
@@ -51,11 +52,12 @@ const App: React.FC = () => {
// 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。
const navigate = (tab: string) => {
const path = TAB_TO_PATH[tab];
const nextTab = tab === 'settings' && !isAdmin ? 'dashboard' : tab;
const path = TAB_TO_PATH[nextTab];
if (path && path !== window.location.pathname) {
window.history.pushState({}, '', path);
}
setActiveTab(tab);
setActiveTab(nextTab);
};
// 浏览器后退/前进同步 tab。
@@ -72,20 +74,39 @@ const App: React.FC = () => {
if (res?.initialized === false) {
setNeedsInit(true);
setIsLoggedIn(false);
setIsAdmin(false);
return;
}
setNeedsInit(false);
if (res?.authenticated) setIsLoggedIn(true);
if (res?.authenticated) {
setIsLoggedIn(true);
setIsAdmin(res.is_admin === true);
} else {
setIsAdmin(false);
}
})
.catch(() => {
setIsLoggedIn(false);
setIsAdmin(false);
})
.catch(() => setIsLoggedIn(false))
.finally(() => setCheckingAuth(false));
const handleLogout = () => setIsLoggedIn(false);
window.addEventListener('auth:logout', handleLogout);
return () => window.removeEventListener('auth:logout', handleLogout);
const handleAuthLogoutEvent = () => {
setIsLoggedIn(false);
setIsAdmin(false);
};
window.addEventListener('auth:logout', handleAuthLogoutEvent);
return () => window.removeEventListener('auth:logout', handleAuthLogoutEvent);
}, []);
useEffect(() => {
if (!checkingAuth && isLoggedIn && !isAdmin && activeTab === 'settings') {
window.history.replaceState({}, '', TAB_TO_PATH.dashboard);
setActiveTab('dashboard');
}
}, [checkingAuth, isLoggedIn, isAdmin, activeTab]);
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setLoginLoading(true);
@@ -95,6 +116,7 @@ const App: React.FC = () => {
const res = await login({ username, password });
if (res.success) {
setIsLoggedIn(true);
setIsAdmin(res.is_admin === true);
} else {
setLoginError(res.message || '登录失败');
}
@@ -106,6 +128,17 @@ const App: React.FC = () => {
}
};
const handleLogout = async () => {
try {
await logout();
} catch (err) {
console.error('退出登录失败', err);
} finally {
setIsLoggedIn(false);
setIsAdmin(false);
}
};
if (checkingAuth) {
return (
@@ -242,8 +275,8 @@ const App: React.FC = () => {
initialDeliveryTarget={deliveryRuleTarget}
onDeliveryTargetHandled={() => setDeliveryRuleTarget(undefined)}
/>;
case 'notifications': return <Notifications />;
case 'settings': return <Settings />;
case 'notifications': return <Notifications isAdmin={isAdmin} />;
case 'settings': return isAdmin ? <Settings /> : <Dashboard />;
default: return <Dashboard />;
}
};
@@ -252,10 +285,9 @@ const App: React.FC = () => {
<div className="flex min-h-screen bg-[#F4F5F7] text-[#111]">
<Sidebar
activeTab={activeTab}
isAdmin={isAdmin}
onNavigate={navigate}
onLogout={() => {
setIsLoggedIn(false);
}}
onLogout={handleLogout}
/>
<main className="flex-1 ml-64 p-8 md:p-12 overflow-y-auto h-screen relative scroll-smooth">
+12 -1
View File
@@ -63,6 +63,7 @@ const AccountList: React.FC = () => {
login_password: '',
show_browser: false,
showLoginPassword: false,
clear_password: false,
});
// AI设置表单状态
@@ -233,6 +234,7 @@ const AccountList: React.FC = () => {
login_password: account.login_password || '',
show_browser: account.show_browser || false,
showLoginPassword: false,
clear_password: false,
});
setActiveModal('edit');
// 并行加载通知渠道列表 + 当前账号已绑定渠道
@@ -794,7 +796,7 @@ const AccountList: React.FC = () => {
<input
type={editForm.showLoginPassword ? 'text' : 'password'}
value={editForm.login_password}
onChange={(e) => setEditForm({ ...editForm, login_password: e.target.value })}
onChange={(e) => setEditForm({ ...editForm, login_password: e.target.value, clear_password: false })}
placeholder="用于自动登录"
className="w-full ios-input px-4 py-3 rounded-xl pr-12"
/>
@@ -806,6 +808,15 @@ const AccountList: React.FC = () => {
{editForm.showLoginPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
</button>
</div>
<label className="mt-3 flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={editForm.clear_password}
onChange={(e) => setEditForm({ ...editForm, clear_password: e.target.checked, login_password: e.target.checked ? '' : editForm.login_password })}
className="w-4 h-4 accent-[#0094f7]"
/>
<span className="text-sm font-bold text-gray-700">清空已保存密码</span>
</label>
</div>
<div className="flex items-center justify-between">
<div>
+20 -4
View File
@@ -110,6 +110,22 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
postage: '',
images: [] as File[]
});
const [publishImagePreviews, setPublishImagePreviews] = useState<{ key: string; url: string }[]>([]);
useEffect(() => {
if (!showPublishModal || publishForm.images.length === 0) {
setPublishImagePreviews([]);
return;
}
const previews = publishForm.images.map((file, index) => ({
key: file.name + index,
url: URL.createObjectURL(file),
}));
setPublishImagePreviews(previews);
return () => {
previews.forEach(preview => URL.revokeObjectURL(preview.url));
};
}, [showPublishModal, publishForm.images]);
const loadItems = async () => {
const itemsList = await getItems();
@@ -689,11 +705,11 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
onChange={e => setPublishForm({...publishForm, images: Array.from(e.target.files || []).slice(0, 9)})}
/>
</label>
{publishForm.images.length > 0 && (
{publishImagePreviews.length > 0 && (
<div className="grid grid-cols-4 sm:grid-cols-6 gap-3">
{publishForm.images.map((file, index) => (
<div key={file.name + index} className="aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100">
<img src={URL.createObjectURL(file)} alt="" className="w-full h-full object-cover" />
{publishImagePreviews.map((preview) => (
<div key={preview.key} className="aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100">
<img src={preview.url} alt="" className="w-full h-full object-cover" />
</div>
))}
</div>
+83 -22
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { NotificationChannel, NotificationChannelType, SystemSettings } from '../types';
import { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../types';
import {
getNotificationChannels,
createNotificationChannel,
@@ -137,25 +137,44 @@ const CHANNEL_TYPES: Record<NotificationChannelType, ChannelTypeMeta> = {
label: '邮件',
icon: Mail,
fields: [
{ key: 'smtp_server', label: 'SMTP 服务器', placeholder: 'smtp.qq.com', required: true },
{ key: 'smtp_port', label: 'SMTP 端口', placeholder: '587', type: 'number', required: true },
{ key: 'smtp_user', label: '发件邮箱', placeholder: '[email protected]', required: true },
{ key: 'smtp_password', label: '密码 / 授权码', type: 'password', required: true },
{ key: 'from', label: '收件邮箱(可选)', placeholder: '留空则发给自己' },
{ key: 'to_email', label: '收件邮箱', placeholder: 'receiver@example.com', required: true },
{ key: 'smtp_server', label: '覆盖 SMTP 服务器', placeholder: 'smtp.qq.com', help: '留空时使用上方系统级 SMTP 配置' },
{ key: 'smtp_port', label: '覆盖 SMTP 端口', placeholder: '587', type: 'number', help: '留空时使用系统级 SMTP 端口' },
{ key: 'smtp_user', label: '覆盖发件邮箱', placeholder: '[email protected]', help: '留空时使用系统级发件邮箱' },
{ key: 'smtp_password', label: '覆盖密码 / 授权码', type: 'password', help: '留空时使用系统级授权码' },
],
guide: {
steps: [
'QQ 邮箱:服务器 smtp.qq.com,端口 587,发件邮箱填你的 QQ 邮箱',
'QQ 邮箱密码栏填「授权码」不是 QQ 密码:QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码',
'163 邮箱:smtp.163.com:587,同样使用授权码',
'Gmail:smtp.gmail.com:587,密码用「应用专用密码」',
'先在页面上方保存系统级 SMTP 服务器、端口、发件邮箱和授权码',
'邮件渠道只需要填写收件邮箱',
'如果某个渠道要使用不同发件邮箱,再填写下面的覆盖 SMTP 字段',
],
note: '收件邮箱留空时,邮件会发到发件邮箱自己。',
note: '收件邮箱会写入 to_email;SMTP 字段留空时后端会复用系统级 SMTP 配置。',
},
},
};
const Notifications: React.FC = () => {
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('、');
};
interface NotificationsProps {
isAdmin?: boolean;
}
const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
const [channels, setChannels] = useState<NotificationChannel[]>([]);
const [loading, setLoading] = useState(true);
const [showModal, setShowModal] = useState(false);
@@ -174,6 +193,7 @@ const Notifications: React.FC = () => {
type: 'bark' as NotificationChannelType,
enabled: true,
config: {} as Record<string, unknown>,
event_types: [] as NotificationEventType[],
});
const load = async () => {
@@ -215,7 +235,14 @@ const Notifications: React.FC = () => {
}
};
useEffect(() => { load(); loadSmtp(); }, []);
useEffect(() => {
load();
if (isAdmin) {
loadSmtp();
} else {
setSmtp({});
}
}, [isAdmin]);
const showToast = (type: 'success' | 'error', text: string) => {
setToast({ type, text });
@@ -224,7 +251,7 @@ const Notifications: React.FC = () => {
const openCreate = () => {
setEditing(null);
setForm({ name: '', type: 'bark', enabled: true, config: {} });
setForm({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] });
setShowModal(true);
};
@@ -235,6 +262,7 @@ const Notifications: React.FC = () => {
type: ch.type,
enabled: ch.enabled,
config: { ...(ch.config || {}) },
event_types: ch.event_types || [],
});
setShowModal(true);
};
@@ -253,7 +281,7 @@ const Notifications: React.FC = () => {
}
setSaving(true);
try {
const payload = { name: form.name.trim(), type: form.type, config: form.config, enabled: form.enabled };
const payload = { name: form.name.trim(), type: form.type, config: form.config, event_types: form.event_types, enabled: form.enabled };
if (editing) {
await updateNotificationChannel(editing.id, payload);
} else {
@@ -283,12 +311,7 @@ const Notifications: React.FC = () => {
const handleToggleEnabled = async (ch: NotificationChannel) => {
try {
// 后端 updateChannel 是全量更新,必须把 name/type/config 一起发回去,
// 否则会被空串覆盖并触发 type 的 CHECK 约束报"更新失败"。
await updateNotificationChannel(ch.id, {
name: ch.name,
type: ch.type,
config: ch.config || {},
enabled: !ch.enabled,
});
setChannels(prev => prev.map(c => c.id === ch.id ? { ...c, enabled: !c.enabled } : c));
@@ -386,6 +409,9 @@ const Notifications: React.FC = () => {
<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
@@ -423,12 +449,13 @@ const Notifications: React.FC = () => {
</div>
)}
{/* SMTP 邮件配置(系统级,用于注册验证码等邮件) */}
{/* 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>
<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" />
@@ -510,6 +537,7 @@ const Notifications: React.FC = () => {
{smtpSaving ? '保存中...' : '保存 SMTP 配置'}
</button>
</section>
)}
{/* 新建/编辑弹窗 */}
{showModal && createPortal(
@@ -600,6 +628,39 @@ const Notifications: React.FC = () => {
))}
</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-[#0094f7] 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-[#0094f7] border-[#0094f7]' : 'border-gray-300'}`}>
{checked && <Check className="w-3 h-3 text-white" />}
</span>
<span className={`text-sm font-bold ${checked ? 'text-[#0094f7]' : '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"
+6 -25
View File
@@ -571,7 +571,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
setEditingReplyRule({
keyword: '',
reply_content: '',
match_type: 'exact',
match_type: 'fuzzy',
enabled: true,
});
setShowReplyModal(true);
@@ -579,12 +579,13 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
const handleSaveReplyRule = async () => {
if (!editingReplyRule || !selectedAccountId) return;
if (!editingReplyRule.keyword?.trim() || !editingReplyRule.reply_content?.trim()) {
const hasReplyContent = Boolean(editingReplyRule.reply_content?.trim() || editingReplyRule.image_url?.trim());
if (!editingReplyRule.keyword?.trim() || !hasReplyContent) {
alert('请填写关键词和回复内容');
return;
}
try {
await updateReplyRule({ ...editingReplyRule, match_type: editingReplyRule.match_type || 'exact', enabled: true }, selectedAccountId);
await updateReplyRule({ ...editingReplyRule, match_type: 'fuzzy', enabled: true }, selectedAccountId);
setShowReplyModal(false);
await loadReplyRules();
alert('保存成功');
@@ -868,11 +869,11 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<div key={rule.id} className="flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg transition-all gap-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-2">
<span className="px-3 py-1 bg-black text-white rounded-lg text-xs font-bold">{rule.match_type === 'exact' ? '精确匹配' : '模糊包含'}</span>
<span className="px-3 py-1 bg-black text-white rounded-lg text-xs font-bold">包含匹配</span>
<h3 className="font-bold text-gray-900">“{rule.keyword}”</h3>
</div>
<div className="bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed">
{rule.reply_content}
{rule.type === 'image' && rule.image_url ? rule.image_url : rule.reply_content}
</div>
</div>
<div className="flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6">
@@ -1311,26 +1312,6 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">匹配类型</label>
<div className="grid grid-cols-2 gap-2">
<button
type="button"
onClick={() => setEditingReplyRule({ ...editingReplyRule, match_type: 'exact' })}
className={`p-3 rounded-xl font-bold transition-all ${editingReplyRule.match_type !== 'fuzzy' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600'}`}
>
精确匹配
</button>
<button
type="button"
onClick={() => setEditingReplyRule({ ...editingReplyRule, match_type: 'fuzzy' })}
className={`p-3 rounded-xl font-bold transition-all ${editingReplyRule.match_type === 'fuzzy' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600'}`}
>
模糊包含
</button>
</div>
</div>
<div className="flex gap-3 pt-4">
<button
onClick={() => setShowReplyModal(false)}
+73 -91
View File
@@ -15,9 +15,32 @@ import {
const DEFAULT_AI_API_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
const LOG_LEVELS = [
{ value: 'debug', label: 'Debug' },
{ value: 'info', label: 'Info' },
{ value: 'warn', label: 'Warn' },
{ value: 'error', label: 'Error' },
];
const SETTINGS_SAVE_OMIT_KEYS = new Set([
'smtp_server',
'smtp_port',
'smtp_user',
'smtp_password',
'smtp_from',
'registration_enabled',
'show_default_login_info',
'login_captcha_enabled',
'item_sync_enabled',
'item_sync_interval',
'item_sync_max_pages',
'default_reply',
]);
const Settings: React.FC = () => {
const [settings, setSettings] = useState<SystemSettings | null>(null);
const [loading, setLoading] = useState(false);
const [loadError, setLoadError] = useState('');
const [saving, setSaving] = useState(false);
const [aiModels, setAiModels] = useState<string[]>([]);
const [modelsLoading, setModelsLoading] = useState(false);
@@ -80,11 +103,16 @@ const Settings: React.FC = () => {
const loadSettings = () => {
setLoading(true);
setLoadError('');
getSystemSettings()
.then(data => {
setSettings(data);
loadAIModels(data);
})
.catch(error => {
setSettings(null);
setLoadError((error as Error).message || '加载配置失败');
})
.finally(() => setLoading(false));
};
@@ -92,9 +120,12 @@ const Settings: React.FC = () => {
if(!settings) return;
setSaving(true);
try {
// SMTP 字段已移至「通知设置」页面,这里不保存,避免覆盖那边已存的值。
const { smtp_server, smtp_port, smtp_user, smtp_password, smtp_from, ...rest } = settings;
await updateSystemSettings(rest);
const persistable = Object.fromEntries(
Object.entries(settings).filter(([key, value]) =>
!SETTINGS_SAVE_OMIT_KEYS.has(key) && value !== undefined && value !== null
)
) as Partial<SystemSettings>;
await updateSystemSettings(persistable);
alert('系统配置已保存');
} catch (e) {
alert('保存失败:' + (e as Error).message);
@@ -143,7 +174,13 @@ const Settings: React.FC = () => {
}
};
if (!settings) return <div className="p-8 text-center text-gray-400">加载配置中...</div>;
if (!settings) {
return (
<div className="p-8 text-center text-gray-400">
{loadError || (loading ? '加载配置中...' : '暂无配置')}
</div>
);
}
const currentModel = settings.ai_model || '';
const visibleAIModels = aiModels;
@@ -183,90 +220,45 @@ const Settings: React.FC = () => {
</h3>
<div className="ios-card rounded-xl p-6 bg-white space-y-4">
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
<div>
<div className="font-bold text-gray-900">允许用户注册</div>
<div className="text-xs text-gray-500 mt-1">开启后允许新用户注册账号</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-3">
<label className="block text-sm font-bold text-gray-800">日志输出等级</label>
<select
value={settings.log_level || 'info'}
onChange={event => setSettings({ ...settings, log_level: event.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
{LOG_LEVELS.map(level => (
<option key={level.value} value={level.value}>{level.label}</option>
))}
</select>
<p className="text-xs text-gray-500">等级越低输出越详细,Debug 适合排查问题</p>
</div>
<div className="space-y-3">
<label className="block text-sm font-bold text-gray-800">日志输出格式</label>
<select
value={settings.log_format || 'text'}
onChange={event => setSettings({ ...settings, log_format: event.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
<option value="text">Text</option>
<option value="json">JSON</option>
</select>
<p className="text-xs text-gray-500">JSON 适合接入集中式日志系统,保存后需重启服务生效</p>
</div>
<button
onClick={() => setSettings({...settings, registration_enabled: !settings.registration_enabled})}
className={`w-14 h-8 rounded-full transition-all relative ${
settings.registration_enabled ? 'bg-[#0094f7]' : 'bg-gray-300'
}`}
>
<div
className={`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${
settings.registration_enabled ? 'left-7' : 'left-1'
}`}
/>
</button>
</div>
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
<div>
<div className="font-bold text-gray-900">显示默认登录信息</div>
<div className="text-xs text-gray-500 mt-1">登录页面显示默认账号密码提示</div>
</div>
<button
onClick={() => setSettings({...settings, show_default_login_info: !settings.show_default_login_info})}
className={`w-14 h-8 rounded-full transition-all relative ${
settings.show_default_login_info ? 'bg-[#0094f7]' : 'bg-gray-300'
}`}
>
<div
className={`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${
settings.show_default_login_info ? 'left-7' : 'left-1'
}`}
/>
</button>
</div>
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
<div>
<div className="font-bold text-gray-900">启用商品自动同步</div>
<div className="text-xs text-gray-500 mt-1">定时自动获取商品信息到本地数据库</div>
</div>
<button
onClick={() => setSettings({...settings, item_sync_enabled: !settings.item_sync_enabled})}
className={`w-14 h-8 rounded-full transition-all relative ${
settings.item_sync_enabled ? 'bg-[#0094f7]' : 'bg-gray-300'
}`}
>
<div
className={`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${
settings.item_sync_enabled ? 'left-7' : 'left-1'
}`}
/>
</button>
</div>
<div className="space-y-3 px-4">
<label className="block text-sm font-bold text-gray-800">商品同步间隔(分钟)</label>
<div className="space-y-3">
<label className="block text-sm font-bold text-gray-800">续期日志保留天数</label>
<input
type="number"
value={Math.round((settings.item_sync_interval || 600) / 60)}
onChange={(e) => {
const minutes = parseInt(e.target.value) || 10;
setSettings({...settings, item_sync_interval: minutes * 60});
}}
value={settings.renewal_log_retention_days ?? 10}
onChange={(e) => setSettings({ ...settings, renewal_log_retention_days: parseInt(e.target.value) || 0 })}
className="w-full ios-input px-4 py-3 rounded-xl"
min="1"
max="1440"
min="0"
max="365"
/>
<p className="text-xs text-gray-500">建议:10-60分钟</p>
</div>
<div className="space-y-3 px-4">
<label className="block text-sm font-bold text-gray-800">每次最多同步页数</label>
<input
type="number"
value={settings.item_sync_max_pages || 5}
onChange={(e) => setSettings({...settings, item_sync_max_pages: parseInt(e.target.value) || 5})}
className="w-full ios-input px-4 py-3 rounded-xl"
min="1"
max="50"
/>
<p className="text-xs text-gray-500">每页20个商品</p>
<p className="text-xs text-gray-500">0 表示不自动清理续期日志</p>
</div>
</div>
</section>
@@ -382,16 +374,6 @@ const Settings: React.FC = () => {
)}
</div>
<div className="space-y-3">
<label className="block text-sm font-bold text-gray-800">默认自动回复内容</label>
<textarea
className="w-full ios-input px-4 py-3 rounded-xl min-h-[100px] text-sm resize-none"
value={settings.default_reply || ''}
onChange={e => setSettings({...settings, default_reply: e.target.value})}
placeholder="设置默认的自动回复内容..."
></textarea>
</div>
<div className="p-3 bg-blue-50 rounded-xl text-xs text-blue-700">
<strong>常见 AI 服务:</strong>
<ul className="list-disc list-inside mt-1 space-y-0.5">
+3 -2
View File
@@ -3,11 +3,12 @@ import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box,
interface SidebarProps {
activeTab: string;
isAdmin?: boolean;
onNavigate: (tab: string) => void;
onLogout: () => void;
}
const Sidebar: React.FC<SidebarProps> = ({ activeTab, onNavigate, onLogout }) => {
const Sidebar: React.FC<SidebarProps> = ({ activeTab, isAdmin = false, onNavigate, onLogout }) => {
const menuItems = [
{ id: 'dashboard', icon: LayoutDashboard, label: '仪表盘' },
{ id: 'accounts', icon: Users, label: '账号管理' },
@@ -16,7 +17,7 @@ const Sidebar: React.FC<SidebarProps> = ({ activeTab, onNavigate, onLogout }) =>
{ id: 'items', icon: Box, label: '商品列表' },
{ id: 'rules', icon: Zap, label: '自动化规则' },
{ id: 'notifications', icon: Bell, label: '通知设置' },
{ id: 'settings', icon: Settings, label: '系统与AI' },
...(isAdmin ? [{ id: 'settings', icon: Settings, label: '系统与AI' }] : []),
];
return (
+26
View File
@@ -34,3 +34,29 @@ test('buildAccountLoginInfoUpdate skips unchanged login info', () => {
expect(payload).toBeNull();
});
test('buildAccountLoginInfoUpdate sends explicit clear password flag', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
{ username: 'old-user', login_password: '', show_browser: false, clear_password: true },
);
expect(payload).toEqual({
username: 'old-user',
show_browser: false,
clear_password: true,
});
});
test('buildAccountLoginInfoUpdate prefers clear password over typed password', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
{ username: 'old-user', login_password: 'new-secret', show_browser: false, clear_password: true },
);
expect(payload).toEqual({
username: 'old-user',
show_browser: false,
clear_password: true,
});
});
+7 -2
View File
@@ -4,11 +4,13 @@ export interface AccountLoginEditForm {
username: string;
login_password: string;
show_browser: boolean;
clear_password?: boolean;
}
export interface AccountLoginInfoPayload {
username: string;
login_password?: string;
clear_password?: boolean;
show_browser: boolean;
}
@@ -19,7 +21,8 @@ export const buildAccountLoginInfoUpdate = (
const usernameChanged = form.username !== (account.username || '');
const showBrowserChanged = form.show_browser !== (account.show_browser || false);
const passwordChanged = form.login_password !== '';
if (!usernameChanged && !showBrowserChanged && !passwordChanged) {
const passwordCleared = form.clear_password === true;
if (!usernameChanged && !showBrowserChanged && !passwordChanged && !passwordCleared) {
return null;
}
@@ -27,7 +30,9 @@ export const buildAccountLoginInfoUpdate = (
username: form.username,
show_browser: form.show_browser,
};
if (passwordChanged) {
if (passwordCleared) {
payload.clear_password = true;
} else if (passwordChanged) {
payload.login_password = form.login_password;
}
return payload;
+79
View File
@@ -26,6 +26,76 @@ describe('frontend navigation routing', () => {
expect([...sidebarIDs].sort()).toEqual([...appRouteIDs].sort());
});
test('logout button invalidates the backend session before clearing UI state', () => {
const app = readFrontendFile('App.tsx');
expect(app).toContain('import { login, logout, verifySession }');
expect(app).toContain('await logout();');
expect(app).toContain('onLogout={handleLogout}');
});
test('settings page does not expose backend-inactive system controls', () => {
const settings = readFrontendFile('components/Settings.tsx');
expect(settings).not.toContain('允许用户注册');
expect(settings).not.toContain('显示默认登录信息');
expect(settings).not.toContain('启用商品自动同步');
expect(settings).not.toContain('商品同步间隔');
expect(settings).not.toContain('默认自动回复内容');
expect(settings).toContain('SETTINGS_SAVE_OMIT_KEYS');
expect(settings).toContain('保存后需重启服务生效');
});
test('admin-only settings navigation is gated by session role', () => {
const app = readFrontendFile('App.tsx');
const sidebar = readFrontendFile('components/Sidebar.tsx');
const settings = readFrontendFile('components/Settings.tsx');
expect(app).toContain('const [isAdmin, setIsAdmin] = useState(false)');
expect(app).toContain('setIsAdmin(res.is_admin === true)');
expect(app).toContain("activeTab === 'settings'");
expect(app).toContain('isAdmin ? <Settings /> : <Dashboard />');
expect(sidebar).toContain('isAdmin = false');
expect(sidebar).toContain("...(isAdmin ? [{ id: 'settings'");
expect(settings).toContain('setLoadError');
});
test('email notification config uses backend recipient field names', () => {
const notifications = readFrontendFile('components/Notifications.tsx');
expect(notifications).toContain('interface NotificationsProps');
expect(notifications).toContain('isAdmin && (');
expect(notifications).toContain("key: 'to_email'");
expect(notifications).toContain('留空时使用上方系统级 SMTP 配置');
expect(notifications).not.toContain("key: 'from'");
expect(notifications).not.toContain('注册验证码');
});
test('keyword reply UI matches contains-based backend behavior', () => {
const rules = readFrontendFile('components/Rules.tsx');
expect(rules).toContain('包含匹配');
expect(rules).not.toContain('精确匹配');
expect(rules).not.toContain('模糊包含');
expect(rules).not.toContain('匹配类型');
});
test('vite proxy does not advertise removed backend routes', () => {
const vite = readFrontendFile('vite.config.ts');
for (const staleRoute of [
'/backup',
'/logs',
'/register',
'/generate-captcha',
'/verify-captcha',
'/geetest',
'/send-verification-code',
]) {
expect(vite).not.toContain(`'${staleRoute}'`);
}
});
test('item delivery shortcut opens existing automation rule modal', () => {
const rules = readFrontendFile('components/Rules.tsx');
const existingRuleBranch = rules.match(/if \(rule\) \{([\s\S]*?)\} else \{/);
@@ -57,4 +127,13 @@ describe('frontend navigation routing', () => {
expect(itemList).toContain('101:1:0;102:2:3');
expect(itemList).toContain('买家购买 3 件时会发送 6 份');
});
test('item publish image previews revoke object urls', () => {
const itemList = readFrontendFile('components/ItemList.tsx');
expect(itemList).toContain('setPublishImagePreviews');
expect(itemList).toContain('URL.createObjectURL(file)');
expect(itemList).toContain('URL.revokeObjectURL(preview.url)');
expect(itemList).not.toContain('src={URL.createObjectURL(file)}');
});
});
+149 -7
View File
@@ -3,15 +3,21 @@ import {
addAccount,
cancelPasswordLogin,
checkPasswordLoginStatus,
createNotificationChannel,
getAccountDetails,
getItems,
getOrders,
getReplyRules,
getShippingRules,
getSystemSettings,
getValidOrders,
logout,
passwordLogin,
updateReplyRule,
updateAccountCookie,
updateAccountLoginInfo,
updateItem,
updateNotificationChannel,
updateShippingRule,
} from './api';
@@ -70,19 +76,27 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
});
});
test('getSystemSettings normalizes boolean strings', async () => {
test('getSystemSettings normalizes numeric renewal retention', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
registration_enabled: 'false',
show_default_login_info: 'true',
item_sync_enabled: '0',
ai_model: 'qwen-plus',
renewal_log_retention_days: 'invalid',
})));
const settings = await getSystemSettings();
expect(settings.registration_enabled).toBe(false);
expect(settings.show_default_login_info).toBe(true);
expect(settings.item_sync_enabled).toBe(false);
expect(settings.ai_model).toBe('qwen-plus');
expect(settings.renewal_log_retention_days).toBe(10);
});
test('logout calls backend session invalidation route', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await logout();
expect(fetchMock).toHaveBeenCalledWith('/logout', expect.objectContaining({
method: 'POST',
credentials: 'include',
}));
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({});
});
test('account cookie APIs include login_method when provided', async () => {
@@ -148,6 +162,32 @@ test('updateAccountLoginInfo sends exactly provided fields', async () => {
});
});
test('updateAccountLoginInfo can request explicit password clearing', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await updateAccountLoginInfo('acc1', { username: 'login-user', clear_password: true, show_browser: false });
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
username: 'login-user',
clear_password: true,
show_browser: false,
});
});
test('updateItem sends only the fields selected by the editor', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await updateItem('acc1', 'item1', { item_title: '改名商品' });
expect(fetchMock).toHaveBeenCalledWith('/items/acc1/item1', expect.objectContaining({
method: 'PUT',
credentials: 'include',
}));
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
item_title: '改名商品',
});
});
test('password login service uses upstream-compatible routes', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid', status: 'processing' }))
@@ -211,6 +251,108 @@ test('getShippingRules exposes buyer reviewed gift rules as automation rules', a
});
});
test('getReplyRules labels keyword matching according to engine contains behavior', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([{
keyword: '发货',
reply: '马上安排',
type: 'image',
image_url: 'https://img.example/reply.png',
}]));
vi.stubGlobal('fetch', fetchMock);
const rules = await getReplyRules('acc1');
expect(fetchMock).toHaveBeenCalledWith('/keywords-with-type/acc1', expect.objectContaining({ method: 'GET' }));
expect(rules[0]).toMatchObject({
keyword: '发货',
reply_content: '马上安排',
match_type: 'fuzzy',
type: 'image',
image_url: 'https://img.example/reply.png',
});
});
test('updateReplyRule preserves keyword image metadata when saving text edits', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse([
{ keyword: '图', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/a.png' },
{ keyword: '发货', reply: '马上安排', item_id: 'item-1', type: 'text', image_url: '' },
]))
.mockResolvedValueOnce(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await updateReplyRule({ id: '1', keyword: '发货', reply_content: '稍后安排' }, 'acc1');
expect(fetchMock).toHaveBeenNthCalledWith(1, '/keywords-with-type/acc1', expect.objectContaining({ method: 'GET' }));
expect(fetchMock).toHaveBeenNthCalledWith(2, '/keywords-with-item-id/acc1', expect.objectContaining({
method: 'POST',
credentials: 'include',
}));
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({
keywords: [
{ keyword: '图', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/a.png' },
{ keyword: '发货', reply: '稍后安排', item_id: 'item-1', type: 'text', image_url: '' },
],
});
});
test('createNotificationChannel persists email recipient as to_email config', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await createNotificationChannel({
name: '邮件通知',
type: 'email',
config: {
smtp_server: 'smtp.example.com',
smtp_port: 587,
smtp_user: '[email protected]',
smtp_password: 'secret',
to_email: '[email protected]',
},
});
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.type).toBe('email');
expect(JSON.parse(body.config)).toMatchObject({
to_email: '[email protected]',
});
expect(JSON.parse(body.config)).not.toHaveProperty('from');
});
test('createNotificationChannel allows email channel to rely on system SMTP settings', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await createNotificationChannel({
name: '邮件通知',
type: 'email',
config: {
to_email: '[email protected]',
},
});
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.type).toBe('email');
expect(JSON.parse(body.config)).toEqual({
to_email: '[email protected]',
});
});
test('updateNotificationChannel supports partial enabled updates', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await updateNotificationChannel('7', { enabled: false });
expect(fetchMock).toHaveBeenCalledWith('/notification-channels/7', expect.objectContaining({
method: 'PUT',
credentials: 'include',
}));
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
enabled: false,
});
});
test('updateShippingRule posts buyer reviewed gift payload to automation-rules', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 1 }));
vi.stubGlobal('fetch', fetchMock);
+77 -45
View File
@@ -2,21 +2,15 @@ import { get, post, put, del, postForm } from '../request';
import {
LoginResponse, AccountDetail, Order, PaginatedResponse,
AdminStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction,
NotificationChannel, NotificationEventType
} from '../types';
const BOOLEAN_SETTING_KEYS = new Set([
'registration_enabled',
'show_default_login_info',
'item_sync_enabled',
]);
const normalizeSettings = (settings: Record<string, any>): SystemSettings => {
const out: Record<string, any> = { ...settings };
for (const key of BOOLEAN_SETTING_KEYS) {
if (key in out) {
out[key] = out[key] === true || out[key] === 'true' || out[key] === '1' || out[key] === 1;
}
if ('renewal_log_retention_days' in out) {
const parsed = Number(out.renewal_log_retention_days);
out.renewal_log_retention_days = Number.isFinite(parsed) ? parsed : 10;
}
return out as SystemSettings;
};
@@ -180,6 +174,7 @@ export const refreshAccountProfile = async (id: string): Promise<any> => {
export const updateAccountLoginInfo = async (id: string, data: {
username?: string;
login_password?: string;
clear_password?: boolean;
show_browser?: boolean;
}): Promise<any> => {
return put(`/cookies/${id}/login-info`, data);
@@ -461,7 +456,7 @@ export const retryFailedItemPublishBatch = async (batchId: string): Promise<any>
return post(`/items/publish-batches/${batchId}/retry-failed`, {});
}
export const updateItem = async (cookieId: string, itemId: string, data: any): Promise<any> => {
export const updateItem = async (cookieId: string, itemId: string, data: Partial<Item>): Promise<any> => {
return put(`/items/${cookieId}/${itemId}`, data);
}
@@ -581,39 +576,65 @@ export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<a
export const deleteShippingRule = async (id: string): Promise<any> => del(`/automation-rules/${id}`);
// Rules - 关键词回复规则 (使用关键词API)
type KeywordRowPayload = {
keyword: string;
reply: string;
item_id: string;
type: 'text' | 'image';
image_url: string;
};
const normalizeKeywordRow = (item: any): KeywordRowPayload => ({
keyword: item?.keyword || '',
reply: item?.reply || '',
item_id: item?.item_id || '',
type: item?.type === 'image' ? 'image' : 'text',
image_url: item?.image_url || '',
});
const getKeywordRowsWithType = async (cookieId: string): Promise<KeywordRowPayload[]> => {
const existing = await get<any>(`/keywords-with-type/${cookieId}`);
return Array.isArray(existing) ? existing.map(normalizeKeywordRow) : [];
};
export const getReplyRules = async (cookieId?: string): Promise<ReplyRule[]> => {
if (!cookieId) return [];
const res = await get<any>(`/keywords-with-item-id/${cookieId}`);
const keywords = Array.isArray(res) ? res : [];
const keywords = await getKeywordRowsWithType(cookieId);
return keywords.map((item: any, index: number) => ({
id: String(index),
keyword: item.keyword || '',
reply_content: item.reply || '',
match_type: 'exact' as const,
enabled: true
match_type: 'fuzzy' as const,
enabled: true,
item_id: item.item_id || '',
type: item.type === 'image' ? 'image' : 'text',
image_url: item.image_url || ''
}));
}
export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string): Promise<any> => {
// 获取现有关键词
const existing = await get<any>(`/keywords-with-item-id/${cookieId}`);
const keywords = Array.isArray(existing) ? existing : [];
const keywords = await getKeywordRowsWithType(cookieId);
// 更新或添加关键词
if (rule.id) {
const index = parseInt(rule.id);
if (index >= 0 && index < keywords.length) {
const current = keywords[index];
keywords[index] = {
keyword: rule.keyword,
reply: rule.reply_content,
item_id: ''
...current,
keyword: rule.keyword ?? current.keyword,
reply: rule.reply_content ?? current.reply,
item_id: rule.item_id ?? current.item_id,
type: rule.type ?? current.type,
image_url: rule.image_url ?? current.image_url,
};
}
} else {
keywords.push({
keyword: rule.keyword,
reply: rule.reply_content,
item_id: ''
keyword: rule.keyword || '',
reply: rule.reply_content || '',
item_id: rule.item_id || '',
type: rule.type || 'text',
image_url: rule.image_url || '',
});
}
@@ -621,8 +642,7 @@ export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string
}
export const deleteReplyRule = async (id: string, cookieId: string): Promise<any> => {
const existing = await get<any>(`/keywords-with-item-id/${cookieId}`);
const keywords = Array.isArray(existing) ? existing : [];
const keywords = await getKeywordRowsWithType(cookieId);
const index = parseInt(id);
if (index >= 0 && index < keywords.length) {
keywords.splice(index, 1);
@@ -639,7 +659,7 @@ export const getSystemSettings = async (): Promise<SystemSettings> => {
export const updateSystemSettings = async (settings: Partial<SystemSettings>): Promise<ApiResponse> => {
// API expects individual PUTs, but we'll loop in the service for convenience or assume bulk endpoint if updated
// Based on docs 12.2, we iterate.
const promises = Object.entries(settings).map(([key, value]) => {
const promises = Object.entries(settings).filter(([, value]) => value !== undefined && value !== null).map(([key, value]) => {
return put(`/system-settings/${key}`, { value: String(value) });
});
await Promise.all(promises);
@@ -669,31 +689,39 @@ export const fetchAIModels = async (baseUrl: string, apiKey: string = ''): Promi
return result.models || [];
};
export const testAIConnection = async (cookieId: string): Promise<ApiResponse> => {
const result = await post<{ success?: boolean; message?: string; reply?: string }>(`/ai-reply-test/${cookieId}`, {
message: '你好,这是一条测试消息',
});
if (result.reply) {
return { success: true, message: `AI 回复: ${result.reply}` };
}
return { success: result.success ?? true, message: result.message || 'AI 连接测试成功' };
}
// Notification Channels
export const getNotificationChannels = async (): Promise<{ success: boolean; data?: any[] }> => {
const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[];
if (typeof raw !== 'string' || !raw.trim()) return [];
try {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[];
} catch {
// fall back to legacy comma/semicolon separated values
}
return raw.split(/[,\s;]+/).map(v => v.trim()).filter(Boolean) as NotificationEventType[];
};
const stringifyNotificationEventTypes = (events?: NotificationEventType[]): string => {
const clean = Array.from(new Set((events || []).filter(Boolean)));
return clean.length > 0 ? JSON.stringify(clean) : '';
};
export const getNotificationChannels = async (): Promise<{ success: boolean; data?: NotificationChannel[] }> => {
const result = await get<any[]>('/notification-channels');
const channels = (result || []).map((item: any) => {
let parsedConfig;
try {
parsedConfig = JSON.parse(item.config);
parsedConfig = typeof item.config === 'string' ? JSON.parse(item.config) : item.config;
} catch {
parsedConfig = undefined;
}
return {
id: String(item.id),
name: item.name,
type: item.type,
type: item.type === 'ding_talk' ? 'dingtalk' : item.type,
config: parsedConfig,
event_types: parseNotificationEventTypes(item.event_types),
enabled: item.enabled,
created_at: item.created_at,
updated_at: item.updated_at,
@@ -702,18 +730,22 @@ export const getNotificationChannels = async (): Promise<{ success: boolean; dat
return { success: true, data: channels };
}
export const createNotificationChannel = async (data: { name: string; type: string; config: Record<string, unknown> }): Promise<ApiResponse> => {
export const createNotificationChannel = async (data: { name: string; type: string; config: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }): Promise<ApiResponse> => {
return post('/notification-channels', {
...data,
config: JSON.stringify(data.config)
config: JSON.stringify(data.config),
event_types: stringifyNotificationEventTypes(data.event_types)
});
}
export const updateNotificationChannel = async (channelId: string, data: { name?: string; type?: string; config?: Record<string, unknown>; enabled?: boolean }): Promise<ApiResponse> => {
export const updateNotificationChannel = async (channelId: string, data: { name?: string; type?: string; config?: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }): Promise<ApiResponse> => {
const payload: Record<string, unknown> = { ...data };
if ('config' in data) {
payload.config = JSON.stringify(data.config);
}
if ('event_types' in data) {
payload.event_types = stringifyNotificationEventTypes(data.event_types);
}
return put(`/notification-channels/${channelId}`, payload);
}
+15
View File
@@ -184,6 +184,9 @@ export interface ReplyRule {
reply_content: string;
match_type: 'exact' | 'fuzzy';
enabled: boolean;
item_id?: string;
type?: 'text' | 'image';
image_url?: string;
}
// Stats
@@ -219,6 +222,9 @@ export interface SystemSettings {
default_reply?: string;
registration_enabled?: boolean;
smtp_server?: string;
log_level?: 'debug' | 'info' | 'warn' | 'error' | string;
log_format?: 'text' | 'json' | string;
renewal_log_retention_days?: number;
[key: string]: any;
}
@@ -244,12 +250,21 @@ export interface DefaultReply {
// 通知渠道
export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email';
export type NotificationEventType =
| 'account_offline'
| 'account_recovered'
| 'account_disabled'
| 'security_verification'
| 'token_renewal'
| 'delivery_result'
| 'system_error';
export interface NotificationChannel {
id: string;
name: string;
type: NotificationChannelType;
config: Record<string, unknown>;
event_types?: NotificationEventType[];
enabled: boolean;
created_at?: string;
updated_at?: string;
-28
View File
@@ -86,14 +86,6 @@ export default defineConfig({
target: 'http://localhost:8080',
changeOrigin: true,
},
'/backup': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/logs': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/login': {
target: 'http://localhost:8080',
changeOrigin: true,
@@ -106,26 +98,6 @@ export default defineConfig({
target: 'http://localhost:8080',
changeOrigin: true,
},
'/register': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/generate-captcha': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/verify-captcha': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/geetest': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/send-verification-code': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/change-password': {
target: 'http://localhost:8080',
changeOrigin: true,