diff --git a/cmd/server/main.go b/cmd/server/main.go index 5a7dd0f..a9080bf 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -28,6 +28,7 @@ import ( "xianyu-go/internal/automation" "xianyu-go/internal/browser" "xianyu-go/internal/db" + "xianyu-go/internal/logging" "xianyu-go/internal/notify" "xianyu-go/internal/renewal" "xianyu-go/internal/server" @@ -41,6 +42,8 @@ func main() { secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)") noBrowser := flag.Bool("no-browser", false, "禁用内置浏览器自动化(扫码风控验证/密码登录/订单抓取将不可用)") verbose := flag.Bool("v", false, "调试日志") + logLevel := flag.String("log-level", "", "日志等级:debug/info/warn/error;默认读取 LOG_LEVEL 或系统设置") + logFormat := flag.String("log-format", "", "日志格式:text/json;默认读取 LOG_FORMAT") initAdmin := flag.Bool("init-admin", false, "初始化或重置 admin 管理员后退出") adminEmail := flag.String("admin-email", "admin@example.com", "初始化 admin 的邮箱") adminPassword := flag.String("admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量") @@ -55,11 +58,28 @@ func main() { resolvedDBURL = *dbPath } - level := slog.LevelInfo - if *verbose { - level = slog.LevelDebug + resolvedLogLevel := strings.TrimSpace(os.Getenv("LOG_LEVEL")) + explicitLogLevel := resolvedLogLevel != "" + if strings.TrimSpace(*logLevel) != "" { + resolvedLogLevel = strings.TrimSpace(*logLevel) + explicitLogLevel = true } - logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level})) + if resolvedLogLevel == "" && *verbose { + resolvedLogLevel = "debug" + explicitLogLevel = true + } + if err := logging.SetLevel(resolvedLogLevel); err != nil { + fmt.Fprintf(os.Stderr, "日志等级无效: %v\n", err) + os.Exit(2) + } + resolvedLogFormat := strings.TrimSpace(os.Getenv("LOG_FORMAT")) + explicitLogFormat := resolvedLogFormat != "" + if strings.TrimSpace(*logFormat) != "" { + resolvedLogFormat = strings.TrimSpace(*logFormat) + explicitLogFormat = true + } + logger := logging.NewLogger(os.Stdout, resolvedLogFormat) + slog.SetDefault(logger) ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() @@ -73,6 +93,19 @@ func main() { logger.Info("数据库已就绪", "dialect", dialect) store := db.NewStore(database, dialect) defer database.Close() + if !explicitLogLevel { + if lv, err := store.Settings.Get(ctx, "log_level"); err == nil && strings.TrimSpace(lv) != "" { + if err := logging.SetLevel(lv); err != nil { + logger.Warn("忽略无效的系统日志等级设置", "value", lv, "err", err) + } + } + } + if !explicitLogFormat { + if format, err := store.Settings.Get(ctx, "log_format"); err == nil && strings.TrimSpace(format) != "" { + logger = logging.NewLogger(os.Stdout, format) + slog.SetDefault(logger) + } + } if *initAdmin { if err := ensureAdmin(ctx, store, *adminEmail, *adminPassword); err != nil { diff --git a/frontend/App.tsx b/frontend/App.tsx index 017870b..19fcc43 100644 --- a/frontend/App.tsx +++ b/frontend/App.tsx @@ -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 ; - case 'settings': return ; + case 'notifications': return ; + case 'settings': return isAdmin ? : ; default: return ; } }; @@ -252,10 +285,9 @@ const App: React.FC = () => {
{ - setIsLoggedIn(false); - }} + onLogout={handleLogout} />
diff --git a/frontend/components/AccountList.tsx b/frontend/components/AccountList.tsx index ba8069e..79ca0a8 100644 --- a/frontend/components/AccountList.tsx +++ b/frontend/components/AccountList.tsx @@ -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 = () => { 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 ? : }
+
diff --git a/frontend/components/ItemList.tsx b/frontend/components/ItemList.tsx index f4a50fd..b8600e7 100644 --- a/frontend/components/ItemList.tsx +++ b/frontend/components/ItemList.tsx @@ -110,6 +110,22 @@ const ItemList: React.FC = ({ 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 = ({ onConfigureDelivery }) => { onChange={e => setPublishForm({...publishForm, images: Array.from(e.target.files || []).slice(0, 9)})} /> - {publishForm.images.length > 0 && ( + {publishImagePreviews.length > 0 && (
- {publishForm.images.map((file, index) => ( -
- + {publishImagePreviews.map((preview) => ( +
+
))}
diff --git a/frontend/components/Notifications.tsx b/frontend/components/Notifications.tsx index ccc1d0e..a19e3d2 100644 --- a/frontend/components/Notifications.tsx +++ b/frontend/components/Notifications.tsx @@ -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 = { 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: 'you@qq.com', 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: 'you@qq.com', 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 = ({ isAdmin = false }) => { const [channels, setChannels] = useState([]); 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, + 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 = () => { {String(v).length > 40 ? String(v).slice(0, 40) + '…' : String(v)} ))}
+
+ 订阅:{notificationEventSummary(ch.event_types)} +
)} - {/* SMTP 邮件配置(系统级,用于注册验证码等邮件) */} + {/* SMTP 邮件配置(系统级,用于邮件通知渠道) */} + {isAdmin && (

SMTP 邮件配置

-

系统级邮件发送服务,用于注册验证码等邮件通知

+

系统级邮件发送服务,供邮件通知渠道复用

@@ -510,6 +537,7 @@ const Notifications: React.FC = () => { {smtpSaving ? '保存中...' : '保存 SMTP 配置'}
+ )} {/* 新建/编辑弹窗 */} {showModal && createPortal( @@ -600,6 +628,39 @@ const Notifications: React.FC = () => { ))}
+
+
+ +

不选择表示接收全部通知;选择后仅接收勾选类型。

+
+
+ {NOTIFICATION_EVENTS.map(event => { + const checked = form.event_types.includes(event.value); + return ( + + ); + })} +
+
+