完善续期通知与前端界面
This commit is contained in:
1 parent
25419c027f
commit
45f895d0c4
64 files changed
+2948
-487
No files matched your search
+37
-4
@@ -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 {
|
||||
|
||||
+45
-13
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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: '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<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"
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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,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 (
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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)}');
|
||||
});
|
||||
});
|
||||
@@ -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: 'from@example.com',
|
||||
smtp_password: 'secret',
|
||||
to_email: 'to@example.com',
|
||||
},
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.type).toBe('email');
|
||||
expect(JSON.parse(body.config)).toMatchObject({
|
||||
to_email: 'to@example.com',
|
||||
});
|
||||
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: 'to@example.com',
|
||||
},
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.type).toBe('email');
|
||||
expect(JSON.parse(body.config)).toEqual({
|
||||
to_email: 'to@example.com',
|
||||
});
|
||||
});
|
||||
|
||||
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
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
+154
-32
@@ -19,6 +19,7 @@ import (
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
@@ -35,6 +36,14 @@ type browserQuickRenewer interface {
|
||||
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
|
||||
}
|
||||
|
||||
type browserTokenCaptchaRecoverer interface {
|
||||
TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error)
|
||||
}
|
||||
|
||||
type tokenCaptchaRequester interface {
|
||||
RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error)
|
||||
}
|
||||
|
||||
// Adapter 实现 engine.Handler 与 automation.OrderDetailFetcher,
|
||||
// 把系统消息、订单详情抓取和密码登录刷新接到浏览器与自动化中心。
|
||||
//
|
||||
@@ -48,6 +57,7 @@ type Adapter struct {
|
||||
notifier notifyNotifier
|
||||
renewSvc xrenew.Service
|
||||
cooldown *renewal.CooldownManager
|
||||
captchaReq tokenCaptchaRequester
|
||||
|
||||
orderFetchMu sync.Mutex
|
||||
lastOrderFetch time.Time
|
||||
@@ -62,6 +72,10 @@ type notifyNotifier interface {
|
||||
NotifyAccountAlert(cookieID, level, title, body string)
|
||||
}
|
||||
|
||||
type notifyEventNotifier interface {
|
||||
NotifyAccountEvent(cookieID, eventType, level, title, body string)
|
||||
}
|
||||
|
||||
// New 构造 Adapter。automation 与 notifier 通过 Set* 后期注入(因创建顺序存在循环:
|
||||
// mgr 依赖 adapter,automation 依赖 mgr,adapter 又依赖 automation)。
|
||||
func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
|
||||
@@ -73,6 +87,7 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
|
||||
browser: browserManagerOrNil(bm),
|
||||
logger: logger,
|
||||
cooldown: renewal.GlobalCooldown,
|
||||
captchaReq: mtop.NewClient(),
|
||||
passwordProcessing: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
@@ -97,6 +112,9 @@ func (a *Adapter) SetBrowser(b browserManager) { a.browser = b }
|
||||
// SetRenewService 覆盖轻量续期服务,便于测试注入本地 HTTP 服务。
|
||||
func (a *Adapter) SetRenewService(s xrenew.Service) { a.renewSvc = s }
|
||||
|
||||
// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器,便于测试隔离网络。
|
||||
func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaReq = r }
|
||||
|
||||
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
|
||||
func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) error {
|
||||
return nil
|
||||
@@ -104,14 +122,143 @@ func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) err
|
||||
|
||||
// OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器,
|
||||
// 推送到该账号已绑定的通知渠道。
|
||||
func (a *Adapter) OnAccountAlert(_ context.Context, cookieID, level, title, body string) {
|
||||
func (a *Adapter) OnAccountAlert(ctx context.Context, cookieID, level, title, body string) {
|
||||
a.OnAccountEvent(ctx, cookieID, classifyAccountAlertEvent(title, body), level, title, body)
|
||||
}
|
||||
|
||||
// OnAccountEvent 把带类型的账号事件转发给通知器。
|
||||
func (a *Adapter) OnAccountEvent(_ context.Context, cookieID, eventType, level, title, body string) {
|
||||
if a.notifier == nil {
|
||||
a.logger.Warn("告警通知未发送:通知器未注入", "account", cookieID, "level", level, "title", title)
|
||||
a.logger.Warn("账号事件通知未发送:通知器未注入", "account", cookieID, "event_type", eventType, "level", level, "title", title)
|
||||
return
|
||||
}
|
||||
if n, ok := a.notifier.(notifyEventNotifier); ok {
|
||||
n.NotifyAccountEvent(cookieID, eventType, level, title, body)
|
||||
return
|
||||
}
|
||||
a.notifier.NotifyAccountAlert(cookieID, level, title, body)
|
||||
}
|
||||
|
||||
func classifyAccountAlertEvent(title, body string) string {
|
||||
msg := strings.ToLower(title + " " + body)
|
||||
switch {
|
||||
case strings.Contains(msg, "风控"), strings.Contains(msg, "验证"),
|
||||
strings.Contains(msg, "滑块"), strings.Contains(msg, "captcha"),
|
||||
strings.Contains(msg, "risk"), strings.Contains(msg, "x5sec"):
|
||||
return engine.EventSecurityVerification
|
||||
case strings.Contains(msg, "禁用"), strings.Contains(msg, "disabled"):
|
||||
return engine.EventAccountDisabled
|
||||
case strings.Contains(msg, "掉线"), strings.Contains(msg, "离线"),
|
||||
strings.Contains(msg, "offline"), strings.Contains(msg, "session"),
|
||||
strings.Contains(msg, "登录凭证已失效"):
|
||||
return engine.EventAccountOffline
|
||||
case strings.Contains(msg, "token"), strings.Contains(msg, "续期"), strings.Contains(msg, "renew"):
|
||||
return engine.EventTokenRenewal
|
||||
default:
|
||||
return engine.EventSystemError
|
||||
}
|
||||
}
|
||||
|
||||
// OnTokenCaptchaVerification 处理 token 刷新触发的闲鱼滑块风控。
|
||||
func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL string) (string, bool) {
|
||||
br, ok := a.browser.(browserTokenCaptchaRecoverer)
|
||||
if a.browser == nil || !ok {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法自动处理", "浏览器自动化未启用,无法自动完成 token 滑块验证。")
|
||||
return "", false
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
var logID int64
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
if id, err := a.store.RiskLogs.Add(ctx, db.RiskControlLog{
|
||||
CookieID: cookieID,
|
||||
EventType: "slider_captcha",
|
||||
EventDescription: "触发场景: Token刷新, URL: " + verificationURL,
|
||||
ProcessingStatus: "processing",
|
||||
}); err == nil {
|
||||
logID = id
|
||||
} else {
|
||||
a.logger.Warn("记录风控日志失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
showBrowser := false
|
||||
metadataJSON := ""
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法保存", "账号存储未初始化,无法保存验证后的 Cookie。")
|
||||
return "", false
|
||||
}
|
||||
|
||||
if d, err := a.store.Cookies.GetDetails(ctx, cookieID); err == nil && d != nil {
|
||||
showBrowser = d.ShowBrowser
|
||||
metadataJSON = d.MetadataJSON
|
||||
}
|
||||
|
||||
provider := func(runCtx context.Context, currentCookies string) (string, bool, string, error) {
|
||||
if a.captchaReq == nil {
|
||||
return "", false, "", nil
|
||||
}
|
||||
deviceID := ""
|
||||
if unb := protocol.TransCookies(currentCookies)["unb"]; unb != "" {
|
||||
deviceID = protocol.GenerateDeviceID(unb)
|
||||
}
|
||||
res, err := a.captchaReq.RequestFreshCaptchaURLContext(runCtx, currentCookies, deviceID)
|
||||
if err != nil || res == nil {
|
||||
return "", false, "", err
|
||||
}
|
||||
return res.VerificationURL, res.TokenOK, res.UpdatedCookies, nil
|
||||
}
|
||||
|
||||
newCookies, err := br.TokenCaptchaRecover(ctx, cookieID, cookieStr, verificationURL, browser.ResolveHeadless(showBrowser), provider)
|
||||
if err != nil {
|
||||
a.logger.Warn("token 风控滑块处理失败", "account", cookieID, "err", err)
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "failed",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块处理失败,耗时: %.2f秒", time.Since(start).Seconds()),
|
||||
CaptchaEngine: "playwright",
|
||||
ErrorMessage: err.Error(),
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证失败", err.Error())
|
||||
return "", false
|
||||
}
|
||||
if strings.TrimSpace(newCookies) == "" {
|
||||
return "", false
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, cookierefresh.MetadataWithoutSnapshot(metadataJSON), time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("保存 token 风控恢复 Cookie 失败", "account", cookieID, "err", err)
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "error",
|
||||
ProcessingResult: "滑块完成但保存 Cookie 失败",
|
||||
CaptchaEngine: "playwright",
|
||||
ErrorMessage: err.Error(),
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "success",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块验证成功,已合并 x5sec,耗时: %.2f秒", time.Since(start).Seconds()),
|
||||
CaptchaEngine: "playwright",
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelInfo,
|
||||
"token 风控验证已自动恢复", "系统已完成滑块验证并更新 x5sec,正在重新获取 token。")
|
||||
return newCookies, true
|
||||
}
|
||||
|
||||
// HandleSystemEvent 把系统卡片事件转发到自动化中心,由自动化规则决定是否执行。
|
||||
func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) error {
|
||||
if a.automation == nil {
|
||||
@@ -229,10 +376,11 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
if err := a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg); err != nil {
|
||||
a.logger.Warn("未配置账号密码时停用账号失败", "account", cookieID, "err", err)
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountDisabled, engine.AlertLevelCritical, "账号已自动禁用", msg)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "no_credentials", "no_credentials", msg)
|
||||
return false
|
||||
}
|
||||
cookies, err := a.browser.PasswordLogin(ctx, d.Username, d.Password, cookieID, "", !d.ShowBrowser)
|
||||
cookies, err := a.browser.PasswordLogin(ctx, d.Username, d.Password, cookieID, "", browser.ResolveHeadless(d.ShowBrowser))
|
||||
if err != nil {
|
||||
a.handlePasswordLoginError(ctx, cookieID, err)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", passwordLoginFailureReason(err), err.Error())
|
||||
@@ -355,9 +503,9 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
|
||||
if br, ok := a.browser.(browserQuickRenewer); ok {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
return br.BrowserQuickRenew(runCtx, d.ID, cookieStr, !d.ShowBrowser)
|
||||
return br.BrowserQuickRenew(runCtx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
|
||||
}
|
||||
m, err := a.browser.CookieRenew(ctx, d.ID, cookieStr, !d.ShowBrowser)
|
||||
m, err := a.browser.CookieRenew(ctx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -417,6 +565,7 @@ func (a *Adapter) handlePasswordLoginError(ctx context.Context, cookieID string,
|
||||
a.logger.Warn("密码登录刷新失败", "account", cookieID, "err", err)
|
||||
if isPasswordLoginDisableError(msg) {
|
||||
_ = a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg)
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountDisabled, engine.AlertLevelCritical, "账号已自动禁用", msg)
|
||||
if isPasswordLoginBadCredentials(msg) {
|
||||
a.markPasswordError(cookieID)
|
||||
}
|
||||
@@ -465,33 +614,6 @@ func (a *Adapter) markPasswordError(cookieID string) {
|
||||
cooldown.MarkPasswordError(cookieID)
|
||||
}
|
||||
|
||||
// saveRecoveredBrowserCookies 执行浏览器恢复动作,统一校验、保存 Cookie 并清理 token 缓存。
|
||||
// Cookie 更新后,旧 accessToken 与旧 session 绑定,继续复用会造成“新 Cookie + 旧 token”
|
||||
// 的逻辑冲突,所以这里必须清除缓存,让 engine 下一轮重新派生 token。
|
||||
func (a *Adapter) saveRecoveredBrowserCookies(ctx context.Context, cookieID string, userID int64, recover func() (map[string]string, error), action string) bool {
|
||||
cookies, err := recover()
|
||||
if err != nil {
|
||||
a.logger.Warn(action+"失败", "account", cookieID, "err", err)
|
||||
return false
|
||||
}
|
||||
cookieStr := browser.MarshalCookies(cookies)
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
a.logger.Warn(action+"失败:浏览器未返回 cookie", "account", cookieID)
|
||||
return false
|
||||
}
|
||||
if err := a.store.Cookies.Save(ctx, cookieID, cookieStr, userID); err != nil {
|
||||
a.logger.Warn(action+"失败:保存 cookie 失败", "account", cookieID, "err", err)
|
||||
return false
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
if err := a.store.Tokens.Clear(ctx, cookieID); err != nil {
|
||||
a.logger.Warn(action+"后清除 token 缓存失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
a.logger.Info(action+" cookie 成功", "account", cookieID)
|
||||
return true
|
||||
}
|
||||
|
||||
// 编译期保证 *Adapter 同时实现 engine.Handler 与 automation.OrderDetailFetcher。
|
||||
var (
|
||||
_ engine.Handler = (*Adapter)(nil)
|
||||
|
||||
@@ -12,19 +12,26 @@ import (
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
// fakeNotifier 记录告警调用,供 OnAccountAlert 断言。
|
||||
type fakeNotifier struct {
|
||||
alerts []struct{ cookieID, level, title, body string }
|
||||
events []struct{ cookieID, eventType, level, title, body string }
|
||||
}
|
||||
|
||||
func (f *fakeNotifier) NotifyAccountAlert(cookieID, level, title, body string) {
|
||||
f.alerts = append(f.alerts, struct{ cookieID, level, title, body string }{cookieID, level, title, body})
|
||||
}
|
||||
|
||||
func (f *fakeNotifier) NotifyAccountEvent(cookieID, eventType, level, title, body string) {
|
||||
f.events = append(f.events, struct{ cookieID, eventType, level, title, body string }{cookieID, eventType, level, title, body})
|
||||
}
|
||||
|
||||
// fakeBrowser 桩实现 browserManager 接口,记录调用并返回可控结果。
|
||||
type fakeBrowser struct {
|
||||
fetchErr error
|
||||
@@ -35,6 +42,15 @@ type fakeBrowser struct {
|
||||
loginErr error
|
||||
loginCookies map[string]string
|
||||
loginCalls int
|
||||
|
||||
tokenCaptchaResult string
|
||||
tokenCaptchaErr error
|
||||
tokenCaptchaCalls int
|
||||
tokenCaptchaURL string
|
||||
tokenCaptchaHeadless bool
|
||||
providerURL string
|
||||
providerTokenOK bool
|
||||
providerUpdated string
|
||||
}
|
||||
|
||||
func (f *fakeBrowser) FetchOrderDetail(_ context.Context, _, _, _ string, _ ...bool) (*browser.OrderDetail, error) {
|
||||
@@ -48,6 +64,30 @@ func (f *fakeBrowser) PasswordLogin(_ context.Context, _, _, _, _ string, _ bool
|
||||
f.loginCalls++
|
||||
return f.loginCookies, f.loginErr
|
||||
}
|
||||
func (f *fakeBrowser) TokenCaptchaRecover(ctx context.Context, _ string, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error) {
|
||||
f.tokenCaptchaCalls++
|
||||
f.tokenCaptchaURL = verificationURL
|
||||
f.tokenCaptchaHeadless = headless
|
||||
if provider != nil {
|
||||
f.providerURL, f.providerTokenOK, f.providerUpdated, _ = provider(ctx, cookieStr)
|
||||
}
|
||||
return f.tokenCaptchaResult, f.tokenCaptchaErr
|
||||
}
|
||||
|
||||
type fakeCaptchaRequester struct {
|
||||
result *mtop.FreshCaptchaResult
|
||||
err error
|
||||
calls int
|
||||
gotCookies string
|
||||
gotDeviceID string
|
||||
}
|
||||
|
||||
func (f *fakeCaptchaRequester) RequestFreshCaptchaURLContext(_ context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error) {
|
||||
f.calls++
|
||||
f.gotCookies = cookiesStr
|
||||
f.gotDeviceID = deviceID
|
||||
return f.result, f.err
|
||||
}
|
||||
|
||||
func newAdapterTestStore(t *testing.T) (*db.Store, func()) {
|
||||
t.Helper()
|
||||
@@ -117,8 +157,65 @@ func TestOnAccountAlert_ForwardedToNotifier(t *testing.T) {
|
||||
n := &fakeNotifier{}
|
||||
a.SetNotifier(n)
|
||||
a.OnAccountAlert(context.Background(), "cid", "warn", "token 失效", "请重新登录")
|
||||
if len(n.alerts) != 1 || n.alerts[0].cookieID != "cid" || n.alerts[0].title != "token 失效" {
|
||||
t.Fatalf("告警未转发: %+v", n.alerts)
|
||||
if len(n.events) != 1 || n.events[0].cookieID != "cid" || n.events[0].title != "token 失效" || n.events[0].eventType != engine.EventTokenRenewal {
|
||||
t.Fatalf("告警未转发为事件通知: events=%+v alerts=%+v", n.events, n.alerts)
|
||||
}
|
||||
a.OnAccountAlert(context.Background(), "cid", "warn", "闲鱼要求滑块验证", "请完成 captcha")
|
||||
if len(n.events) != 2 || n.events[1].eventType != engine.EventSecurityVerification {
|
||||
t.Fatalf("风控告警应分类为 security_verification: events=%+v alerts=%+v", n.events, n.alerts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
fb := &fakeBrowser{tokenCaptchaResult: "unb=1; _m_h5_tk=fresh; x5sec=ok;"}
|
||||
req := &fakeCaptchaRequester{result: &mtop.FreshCaptchaResult{
|
||||
VerificationURL: "https://fresh.example/captcha",
|
||||
UpdatedCookies: "unb=1; _m_h5_tk=fresh;",
|
||||
}}
|
||||
notifier := &fakeNotifier{}
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(fb)
|
||||
a.SetTokenCaptchaRequester(req)
|
||||
a.SetNotifier(notifier)
|
||||
|
||||
newCookies, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1; _m_h5_tk=tk;", "https://old.example/captcha")
|
||||
if !ok {
|
||||
t.Fatal("token captcha recovery should succeed")
|
||||
}
|
||||
if !strings.Contains(newCookies, "x5sec=ok") {
|
||||
t.Fatalf("returned cookies should contain x5sec: %q", newCookies)
|
||||
}
|
||||
if fb.tokenCaptchaCalls != 1 || fb.tokenCaptchaURL != "https://old.example/captcha" {
|
||||
t.Fatalf("browser captcha call mismatch: calls=%d url=%q", fb.tokenCaptchaCalls, fb.tokenCaptchaURL)
|
||||
}
|
||||
if fb.providerURL != "https://fresh.example/captcha" || fb.providerUpdated == "" {
|
||||
t.Fatalf("provider result not passed through: url=%q updated=%q", fb.providerURL, fb.providerUpdated)
|
||||
}
|
||||
if req.calls != 1 || req.gotDeviceID == "" {
|
||||
t.Fatalf("fresh captcha requester not called correctly: calls=%d device=%q", req.calls, req.gotDeviceID)
|
||||
}
|
||||
saved, err := store.Cookies.GetValue(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatalf("GetValue: %v", err)
|
||||
}
|
||||
if !strings.Contains(saved, "x5sec=ok") {
|
||||
t.Fatalf("saved cookies should contain x5sec: %q", saved)
|
||||
}
|
||||
var status, engineName string
|
||||
if err := store.DB.QueryRowContext(ctx,
|
||||
`SELECT processing_status, captcha_engine FROM risk_control_logs WHERE cookie_id='cid' ORDER BY id DESC LIMIT 1`).
|
||||
Scan(&status, &engineName); err != nil {
|
||||
t.Fatalf("query risk log: %v", err)
|
||||
}
|
||||
if status != "success" || engineName != "playwright" {
|
||||
t.Fatalf("risk log status=%q engine=%q", status, engineName)
|
||||
}
|
||||
if len(notifier.events) != 1 || notifier.events[0].eventType != engine.EventSecurityVerification || notifier.events[0].level != engine.AlertLevelInfo {
|
||||
t.Fatalf("security recovery notification missing: %+v", notifier.events)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -627,6 +627,20 @@ func (c *Center) markEventFacts(ctx context.Context, task Task) {
|
||||
if task.OrderID == "" {
|
||||
return
|
||||
}
|
||||
if err := c.store.Orders.Upsert(ctx, task.OrderID, db.OrderUpsertOpts{
|
||||
CookieID: task.AccountID,
|
||||
ItemID: task.ItemID,
|
||||
BuyerID: task.BuyerID,
|
||||
ChatID: task.ChatID,
|
||||
OrderStatus: task.OrderStatus,
|
||||
SpecName: task.SpecName,
|
||||
SpecValue: task.SpecValue,
|
||||
Quantity: task.Quantity,
|
||||
Amount: task.Amount,
|
||||
}); err != nil {
|
||||
c.logger.Warn("记录自动化事件事实前创建订单失败", "order_id", task.OrderID, "trigger", task.TriggerType, "err", err)
|
||||
return
|
||||
}
|
||||
switch task.TriggerType {
|
||||
case TriggerOrderPaid:
|
||||
_ = c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "paid_at")
|
||||
|
||||
@@ -111,6 +111,60 @@ func TestCenterOrderPaidFetchesOrderDetailMatchesSpecAndQuantity(t *testing.T) {
|
||||
if order.SpecName != "套餐" || order.SpecValue != "90天" || order.Quantity != "2" {
|
||||
t.Fatalf("订单详情未写入: %+v", order)
|
||||
}
|
||||
if order.PaidAt == "" {
|
||||
t.Fatalf("首次付款事件创建订单时应记录 paid_at: %+v", order)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCenterBuyerReviewedFirstEventRecordsReviewTime(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
|
||||
_, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", ItemID: "item-review", Name: "评价赠品", TriggerType: TriggerBuyerReviewed,
|
||||
Enabled: true, Priority: 100,
|
||||
Actions: []db.AutomationActionInput{
|
||||
{ActionType: ActionSendText, MessageTemplate: "谢谢评价", Enabled: true, SortOrder: 1},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create review rule: %v", err)
|
||||
}
|
||||
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
if err := center.HandleTask(ctx, Task{
|
||||
Source: "ws", AccountID: "cid", TriggerType: TriggerBuyerReviewed,
|
||||
ChatID: "chat-review", OrderID: "order-review", ItemID: "item-review", BuyerID: "buyer-review",
|
||||
Raw: map[string]any{"message_id": "review-1"},
|
||||
}); err != nil {
|
||||
t.Fatalf("HandleTask: %v", err)
|
||||
}
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "谢谢评价" {
|
||||
t.Fatalf("评价赠品发送异常: %v", sender.texts)
|
||||
}
|
||||
order, err := store.Orders.Get(ctx, "order-review")
|
||||
if err != nil {
|
||||
t.Fatalf("Get order-review: %v", err)
|
||||
}
|
||||
if order.BuyerReviewedAt == "" {
|
||||
t.Fatalf("首次评价事件创建订单时应记录 buyer_reviewed_at: %+v", order)
|
||||
}
|
||||
sysShipped := true
|
||||
if err := store.Orders.Upsert(ctx, "order-review", db.OrderUpsertOpts{
|
||||
CookieID: "cid", ItemID: "item-review", BuyerID: "buyer-review", ChatID: "chat-review", SystemShipped: &sysShipped,
|
||||
}); err != nil {
|
||||
t.Fatalf("mark shipped: %v", err)
|
||||
}
|
||||
due, err := store.Automation.DueReviewRequestOrders(ctx, 200)
|
||||
if err != nil {
|
||||
t.Fatalf("DueReviewRequestOrders: %v", err)
|
||||
}
|
||||
if len(due) != 0 {
|
||||
t.Fatalf("已评价订单不应进入求评价扫描: %+v", due)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCenterOrderPaidSendsAllCardActionsForSameSpec(t *testing.T) {
|
||||
@@ -255,7 +309,7 @@ func TestCenterOrderPaidSendsCardBeforeConfirmShipment(t *testing.T) {
|
||||
|
||||
// recordingNotifier 记录所有 NotifyDelivery 调用,用于断言 automation.Center 接线。
|
||||
type recordingNotifier struct {
|
||||
mu sync.Mutex
|
||||
mu sync.Mutex
|
||||
calls []struct {
|
||||
accountID, buyerID, itemID, message, chatID string
|
||||
}
|
||||
|
||||
@@ -331,6 +331,17 @@ func (m *Manager) newEphemeralRefreshContext(ctx context.Context, cookieID, cook
|
||||
}
|
||||
|
||||
func quickRenewHeadless(headless bool) bool {
|
||||
return resolveHeadlessRequest(headless)
|
||||
}
|
||||
|
||||
// ResolveHeadless returns the browser headless mode from account ShowBrowser plus
|
||||
// the optional BROWSER_HEADLESS override. All browser-backed login/renewal flows
|
||||
// use this resolver so headed/headless only changes visibility, not behavior.
|
||||
func ResolveHeadless(showBrowser bool) bool {
|
||||
return resolveHeadlessRequest(!showBrowser)
|
||||
}
|
||||
|
||||
func resolveHeadlessRequest(headless bool) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv("BROWSER_HEADLESS"))) {
|
||||
case "true", "1", "yes", "on":
|
||||
return true
|
||||
|
||||
@@ -63,6 +63,24 @@ func TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveHeadlessUsesShowBrowserConsistently(t *testing.T) {
|
||||
t.Setenv("BROWSER_HEADLESS", "")
|
||||
if !ResolveHeadless(false) {
|
||||
t.Fatal("show_browser=false should run headless")
|
||||
}
|
||||
if ResolveHeadless(true) {
|
||||
t.Fatal("show_browser=true should run headed")
|
||||
}
|
||||
t.Setenv("BROWSER_HEADLESS", "true")
|
||||
if !ResolveHeadless(true) {
|
||||
t.Fatal("env override should force headless")
|
||||
}
|
||||
t.Setenv("BROWSER_HEADLESS", "false")
|
||||
if ResolveHeadless(false) {
|
||||
t.Fatal("env override should force headed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookiesRefreshHeadlessUsesAccountPreference(t *testing.T) {
|
||||
t.Setenv("BROWSER_HEADLESS", "")
|
||||
if !cookiesRefreshHeadless(true) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
)
|
||||
|
||||
// TokenCaptchaURLProvider is called after Chromium is ready, so the token API
|
||||
// can return a fresh punish URL instead of using one that expired while waiting.
|
||||
type TokenCaptchaURLProvider func(ctx context.Context, currentCookies string) (url string, tokenOK bool, updatedCookies string, err error)
|
||||
|
||||
// TokenCaptchaRecover solves a token-refresh captcha and returns cookies with x5sec merged in.
|
||||
func (m *Manager) TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider TokenCaptchaURLProvider) (string, error) {
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
return "", fmt.Errorf("Cookie为空,无法处理 token 风控验证")
|
||||
}
|
||||
if strings.TrimSpace(verificationURL) == "" {
|
||||
return "", fmt.Errorf("验证链接为空")
|
||||
}
|
||||
|
||||
currentCookies := cookieStr
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, quickRenewHeadless(headless))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer release()
|
||||
|
||||
targetURL := verificationURL
|
||||
if provider != nil {
|
||||
freshURL, tokenOK, updated, err := provider(ctx, currentCookies)
|
||||
if err != nil {
|
||||
m.logger.Warn("token风控验证前重取链接失败,沿用原链接", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
if strings.TrimSpace(updated) != "" && updated != currentCookies {
|
||||
currentCookies = updated
|
||||
if err := addCookieStr(bctx, currentCookies); err != nil {
|
||||
m.logger.Warn("token风控验证注入重取后的 Cookie 失败", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
if tokenOK {
|
||||
m.logger.Info("token风控验证前重取 token 已成功,无需滑块", "cookieID", cookieID)
|
||||
return currentCookies, nil
|
||||
}
|
||||
if strings.TrimSpace(freshURL) != "" {
|
||||
targetURL = freshURL
|
||||
}
|
||||
}
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
if _, err := page.Goto(targetURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(30000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("token风控验证页面访问异常", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
|
||||
content, _ := page.Content()
|
||||
scratch := isScratchCaptcha(content)
|
||||
if err := solveSlider(page, scratch, m.logger); err != nil {
|
||||
return "", err
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
all, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("提取 token 风控 cookie 失败: %w", err)
|
||||
}
|
||||
x5 := make(map[string]string)
|
||||
hasX5Sec := false
|
||||
for _, c := range all {
|
||||
name := strings.ToLower(c.Name)
|
||||
if strings.HasPrefix(name, "x5") || strings.Contains(name, "x5sec") {
|
||||
x5[c.Name] = c.Value
|
||||
if name == "x5sec" && strings.TrimSpace(c.Value) != "" {
|
||||
hasX5Sec = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasX5Sec {
|
||||
return "", fmt.Errorf("滑块验证未获取到 x5sec cookie")
|
||||
}
|
||||
merged := parseCookieStr(currentCookies)
|
||||
for k, v := range x5 {
|
||||
merged[k] = v
|
||||
}
|
||||
m.logger.Info("token风控验证成功", "cookieID", cookieID, "x5_cookie_count", len(x5))
|
||||
return cookieMarshal(merged), nil
|
||||
}
|
||||
+63
-16
@@ -150,18 +150,19 @@ func (i *ItemReplies) AllForUser(ctx context.Context, cookieID string) ([]ItemRe
|
||||
|
||||
// NotificationChannelRow 通知渠道完整行(含 id)。
|
||||
type NotificationChannelRow struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
EventTypes string `json:"event_types,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// AllChannelsForUser 取某用户全部通知渠道。
|
||||
func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([]NotificationChannelRow, error) {
|
||||
rows, err := n.DB.QueryContext(ctx,
|
||||
`SELECT id, name, type, config, enabled, COALESCE(user_id,1) FROM notification_channels
|
||||
`SELECT id, name, type, config, COALESCE(event_types,''), enabled, COALESCE(user_id,1) FROM notification_channels
|
||||
WHERE user_id=? ORDER BY id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -171,7 +172,7 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([
|
||||
for rows.Next() {
|
||||
var c NotificationChannelRow
|
||||
var enabled int
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &enabled, &c.UserID); err != nil {
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Enabled = enabled != 0
|
||||
@@ -183,30 +184,77 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([
|
||||
// CreateChannel 创建通知渠道。
|
||||
func (n *Notifications) CreateChannel(ctx context.Context, c *NotificationChannelRow) (int64, error) {
|
||||
return insertReturningID(ctx, n.DB, n.Dialect,
|
||||
`INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES (?,?,?,?,?)`,
|
||||
c.Name, c.Type, c.Config, boolToInt(c.Enabled), c.UserID)
|
||||
`INSERT INTO notification_channels (name, type, config, event_types, enabled, user_id) VALUES (?,?,?,?,?,?)`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.UserID)
|
||||
}
|
||||
|
||||
// UpdateChannel 更新通知渠道。
|
||||
func (n *Notifications) UpdateChannel(ctx context.Context, c *NotificationChannelRow) error {
|
||||
_, err := n.DB.ExecContext(ctx,
|
||||
`UPDATE notification_channels SET name=?, type=?, config=?, enabled=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
c.Name, c.Type, c.Config, boolToInt(c.Enabled), c.ID)
|
||||
`UPDATE notification_channels SET name=?, type=?, config=?, event_types=?, enabled=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetChannelRowForUser 按用户取单个通知渠道。未找到返回 nil。
|
||||
func (n *Notifications) GetChannelRowForUser(ctx context.Context, id, userID int64) (*NotificationChannelRow, error) {
|
||||
row := n.DB.QueryRowContext(ctx,
|
||||
`SELECT id, name, type, config, COALESCE(event_types,''), enabled, COALESCE(user_id,1)
|
||||
FROM notification_channels WHERE id=? AND user_id=?`, id, userID)
|
||||
var c NotificationChannelRow
|
||||
var enabled int
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
c.Enabled = enabled != 0
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// UpdateChannelForUser 更新指定用户拥有的通知渠道。
|
||||
func (n *Notifications) UpdateChannelForUser(ctx context.Context, c *NotificationChannelRow, userID int64) error {
|
||||
res, err := n.DB.ExecContext(ctx,
|
||||
`UPDATE notification_channels
|
||||
SET name=?, type=?, config=?, event_types=?, enabled=?, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND user_id=?`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.ID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := res.RowsAffected()
|
||||
if err == nil && rows == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteChannel 删除通知渠道。
|
||||
func (n *Notifications) DeleteChannel(ctx context.Context, id int64) error {
|
||||
_, err := n.DB.ExecContext(ctx, `DELETE FROM notification_channels WHERE id=?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteChannelForUser 删除指定用户拥有的通知渠道。
|
||||
func (n *Notifications) DeleteChannelForUser(ctx context.Context, id, userID int64) error {
|
||||
res, err := n.DB.ExecContext(ctx, `DELETE FROM notification_channels WHERE id=? AND user_id=?`, id, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := res.RowsAffected()
|
||||
if err == nil && rows == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetChannel 按 ID 取单个通知渠道(含 config)。未找到返回 nil。
|
||||
func (n *Notifications) GetChannel(ctx context.Context, id int64) (*NotificationChannel, error) {
|
||||
row := n.DB.QueryRowContext(ctx,
|
||||
`SELECT id, name, type, config FROM notification_channels WHERE id=?`, id)
|
||||
`SELECT id, name, type, config, COALESCE(event_types,'') FROM notification_channels WHERE id=?`, id)
|
||||
var c NotificationChannel
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config); err != nil {
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -332,8 +380,7 @@ func (s *SystemSettings) Set(ctx context.Context, key, value string) error {
|
||||
|
||||
// PublicSystemKeys 是公开设置键白名单(前端登录页等无需登录可读)。
|
||||
var PublicSystemKeys = map[string]bool{
|
||||
"theme_color": true, "registration_enabled": true,
|
||||
"show_default_login_info": true,
|
||||
"theme_color": true,
|
||||
}
|
||||
|
||||
// Public 取公开设置子集。
|
||||
|
||||
@@ -252,9 +252,10 @@ func TestSettings_Public(t *testing.T) {
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
// 写入一个公开 key + 一个私有 key。
|
||||
// 写入一个公开 key + 几个遗留/私有 key。
|
||||
s.Settings.Set(ctx, "theme_color", "blue")
|
||||
s.Settings.Set(ctx, "registration_enabled", "true")
|
||||
s.Settings.Set(ctx, "show_default_login_info", "true")
|
||||
s.Settings.Set(ctx, "private_secret", "topsecret")
|
||||
s.Settings.Set(ctx, "qq_reply_secret_key", "should-not-leak")
|
||||
|
||||
@@ -262,7 +263,7 @@ func TestSettings_Public(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Public: %v", err)
|
||||
}
|
||||
if pub["theme_color"] != "blue" || pub["registration_enabled"] != "true" {
|
||||
if pub["theme_color"] != "blue" {
|
||||
t.Fatalf("公开 key 缺失: %#v", pub)
|
||||
}
|
||||
// 私有 key 不应出现。
|
||||
@@ -275,9 +276,11 @@ func TestSettings_Public(t *testing.T) {
|
||||
if _, ok := pub["login_captcha_enabled"]; ok {
|
||||
t.Fatal("未实现的登录验证码开关不应公开")
|
||||
}
|
||||
// 白名单内其它默认 key(show_default_login_info)也应可见。
|
||||
if pub["show_default_login_info"] != "true" {
|
||||
t.Fatalf("show_default_login_info 应为 true, got %q", pub["show_default_login_info"])
|
||||
if _, ok := pub["registration_enabled"]; ok {
|
||||
t.Fatal("未实现的注册开关不应公开")
|
||||
}
|
||||
if _, ok := pub["show_default_login_info"]; ok {
|
||||
t.Fatal("未使用的默认登录提示开关不应公开")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
// TestMigrate_AppliesCleanSchema 在临时库上跑迁移,验证全量 schema 干净落地、
|
||||
@@ -35,6 +37,18 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
|
||||
{"users", "is_admin"},
|
||||
{"sessions", "session_id"},
|
||||
{"notification_channels", "user_id"},
|
||||
{"notification_channels", "event_types"},
|
||||
{"message_notifications", "event_types"},
|
||||
{"scheduled_cookies_refresh_log", "step_details"},
|
||||
{"scheduled_cookies_refresh_log", "renew_method"},
|
||||
{"scheduled_cookies_refresh_log", "duration_ms"},
|
||||
{"scheduled_cookies_refresh_log", "request_count"},
|
||||
{"scheduled_login_renew_log", "step_details"},
|
||||
{"scheduled_login_renew_log", "updated_cookie_count"},
|
||||
{"scheduled_api_cookie_renew_log", "step_details"},
|
||||
{"scheduled_api_cookie_renew_log", "request_count"},
|
||||
{"risk_control_logs", "processing_status"},
|
||||
{"risk_control_logs", "duration_ms"},
|
||||
}
|
||||
for _, c := range checks {
|
||||
if !columnExists(t, db, c.table, c.col) {
|
||||
@@ -52,6 +66,14 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
|
||||
if err != nil || val != "" {
|
||||
t.Errorf("qq_reply_secret_key 应为空(无默认值安全基线): val=%q err=%v", val, err)
|
||||
}
|
||||
err = db.QueryRow(`SELECT value FROM system_settings WHERE key='log_level'`).Scan(&val)
|
||||
if err != nil || val != "info" {
|
||||
t.Errorf("log_level 默认设置异常: val=%q err=%v", val, err)
|
||||
}
|
||||
err = db.QueryRow(`SELECT value FROM system_settings WHERE key='renewal_log_retention_days'`).Scan(&val)
|
||||
if err != nil || val != "10" {
|
||||
t.Errorf("renewal_log_retention_days 默认设置异常: val=%q err=%v", val, err)
|
||||
}
|
||||
|
||||
// 二次 Open 应幂等(迁移不重复执行、不报错)。
|
||||
if err := db.Close(); err != nil {
|
||||
@@ -82,3 +104,61 @@ func columnExists(t *testing.T, db *sql.DB, table, col string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestMigration14DownUpSQLite(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
dbPath := filepath.Join(tmp, "rollback.db")
|
||||
ctx := context.Background()
|
||||
d, _, err := Open(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
if err := goose.SetDialect("sqlite3"); err != nil {
|
||||
t.Fatalf("goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down latest migration: %v", err)
|
||||
}
|
||||
if columnExists(t, d, "notification_channels", "event_types") {
|
||||
t.Fatal("event_types should be removed after migration 14 down")
|
||||
}
|
||||
if tableExists(t, d, "risk_control_logs") {
|
||||
t.Fatal("risk_control_logs should be removed after migration 14 down")
|
||||
}
|
||||
|
||||
if err := goose.Up(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("up after down: %v", err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
table string
|
||||
col string
|
||||
}{
|
||||
{"notification_channels", "event_types"},
|
||||
{"message_notifications", "event_types"},
|
||||
{"scheduled_cookies_refresh_log", "step_details"},
|
||||
{"scheduled_login_renew_log", "updated_cookie_count"},
|
||||
{"scheduled_api_cookie_renew_log", "request_count"},
|
||||
{"risk_control_logs", "processing_status"},
|
||||
} {
|
||||
if !columnExists(t, d, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
}
|
||||
}
|
||||
var val string
|
||||
if err := d.QueryRow(`SELECT value FROM system_settings WHERE key='renewal_log_retention_days'`).Scan(&val); err != nil || val != "10" {
|
||||
t.Fatalf("renewal_log_retention_days after re-up: val=%q err=%v", val, err)
|
||||
}
|
||||
}
|
||||
|
||||
func tableExists(t *testing.T, db *sql.DB, table string) bool {
|
||||
t.Helper()
|
||||
var name string
|
||||
err := db.QueryRow(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`, table).Scan(&name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return name == table
|
||||
}
|
||||
@@ -4,41 +4,41 @@ ALTER TABLE cookies ADD COLUMN last_refresh_at BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE cookie_status ADD COLUMN disable_reason TEXT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS cookie_refresh_schedules (
|
||||
cookie_id VARCHAR(191) PRIMARY KEY,
|
||||
cookie_id VARCHAR(255) PRIMARY KEY,
|
||||
expire_at BIGINT NOT NULL DEFAULT 0,
|
||||
disabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||
consecutive_failures INT NOT NULL DEFAULT 0,
|
||||
last_error TEXT NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_cookie_refresh_schedules_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
);
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scheduled_cookies_refresh_log (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
updated_cookie_names TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scheduled_login_renew_log (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
updated_cookie_names TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scheduled_api_cookie_renew_log (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
updated_cookie_names TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS scheduled_api_cookie_renew_log;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
-- +goose Up
|
||||
DROP PROCEDURE IF EXISTS add_xianyu_column_if_missing;
|
||||
-- +goose StatementBegin
|
||||
CREATE PROCEDURE add_xianyu_column_if_missing(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64),
|
||||
IN p_column_definition TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @ddl = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN ', p_column_definition);
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CALL add_xianyu_column_if_missing('notification_channels', 'event_types', CONCAT('`event_types` VARCHAR(512) NOT NULL DEFAULT ', QUOTE('')));
|
||||
CALL add_xianyu_column_if_missing('message_notifications', 'event_types', CONCAT('`event_types` VARCHAR(512) NOT NULL DEFAULT ', QUOTE('')));
|
||||
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'step_details', '`step_details` TEXT');
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'renew_method', CONCAT('`renew_method` VARCHAR(64) NOT NULL DEFAULT ', QUOTE('')));
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'duration_ms', '`duration_ms` BIGINT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'request_count', '`request_count` INT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'response_content', '`response_content` MEDIUMTEXT');
|
||||
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'step_details', '`step_details` TEXT');
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'renew_method', CONCAT('`renew_method` VARCHAR(64) NOT NULL DEFAULT ', QUOTE('')));
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'duration_ms', '`duration_ms` BIGINT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'request_count', '`request_count` INT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'response_content', '`response_content` MEDIUMTEXT');
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'updated_cookie_count', '`updated_cookie_count` INT NOT NULL DEFAULT 0');
|
||||
|
||||
CALL add_xianyu_column_if_missing('scheduled_api_cookie_renew_log', 'step_details', '`step_details` TEXT');
|
||||
CALL add_xianyu_column_if_missing('scheduled_api_cookie_renew_log', 'renew_method', CONCAT('`renew_method` VARCHAR(64) NOT NULL DEFAULT ', QUOTE('')));
|
||||
CALL add_xianyu_column_if_missing('scheduled_api_cookie_renew_log', 'duration_ms', '`duration_ms` BIGINT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_api_cookie_renew_log', 'request_count', '`request_count` INT NOT NULL DEFAULT 0');
|
||||
|
||||
DROP PROCEDURE IF EXISTS add_xianyu_column_if_missing;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS risk_control_logs (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
event_type VARCHAR(64) NOT NULL DEFAULT 'slider_captcha',
|
||||
event_description TEXT,
|
||||
processing_result TEXT,
|
||||
processing_status VARCHAR(32) NOT NULL DEFAULT 'processing',
|
||||
captcha_engine VARCHAR(32) NOT NULL DEFAULT '',
|
||||
error_message TEXT,
|
||||
duration_ms BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_risk_control_logs_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
INSERT IGNORE INTO system_settings (`key`, value, description) VALUES
|
||||
('log_level', 'info', '日志输出等级:debug/info/warn/error'),
|
||||
('log_format', 'text', '日志输出格式:text/json'),
|
||||
('renewal_log_retention_days', '10', '续期日志保留天数');
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS risk_control_logs;
|
||||
DELETE FROM system_settings WHERE `key` IN ('log_level', 'log_format', 'renewal_log_retention_days');
|
||||
|
||||
DROP PROCEDURE IF EXISTS drop_xianyu_column_if_exists;
|
||||
-- +goose StatementBegin
|
||||
CREATE PROCEDURE drop_xianyu_column_if_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @ddl = CONCAT('ALTER TABLE `', p_table_name, '` DROP COLUMN `', p_column_name, '`');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CALL drop_xianyu_column_if_exists('notification_channels', 'event_types');
|
||||
CALL drop_xianyu_column_if_exists('message_notifications', 'event_types');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'step_details');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'renew_method');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'duration_ms');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'request_count');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'response_content');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'step_details');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'renew_method');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'duration_ms');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'request_count');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'response_content');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'updated_cookie_count');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_api_cookie_renew_log', 'step_details');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_api_cookie_renew_log', 'renew_method');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_api_cookie_renew_log', 'duration_ms');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_api_cookie_renew_log', 'request_count');
|
||||
|
||||
DROP PROCEDURE IF EXISTS drop_xianyu_column_if_exists;
|
||||
@@ -0,0 +1,63 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE notification_channels ADD COLUMN IF NOT EXISTS event_types TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE message_notifications ADD COLUMN IF NOT EXISTS event_types TEXT NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS duration_ms BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS request_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS response_content TEXT NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS duration_ms BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS request_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS response_content TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS updated_cookie_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN IF NOT EXISTS step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN IF NOT EXISTS renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN IF NOT EXISTS duration_ms BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN IF NOT EXISTS request_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS risk_control_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
cookie_id TEXT NOT NULL REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
event_type TEXT NOT NULL DEFAULT 'slider_captcha',
|
||||
event_description TEXT NOT NULL DEFAULT '',
|
||||
processing_result TEXT NOT NULL DEFAULT '',
|
||||
processing_status TEXT NOT NULL DEFAULT 'processing',
|
||||
captcha_engine TEXT NOT NULL DEFAULT '',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
duration_ms BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO system_settings (key, value, description) VALUES
|
||||
('log_level', 'info', '日志输出等级:debug/info/warn/error'),
|
||||
('log_format', 'text', '日志输出格式:text/json'),
|
||||
('renewal_log_retention_days', '10', '续期日志保留天数')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS risk_control_logs;
|
||||
DELETE FROM system_settings WHERE key IN ('log_level', 'log_format', 'renewal_log_retention_days');
|
||||
|
||||
ALTER TABLE notification_channels DROP COLUMN IF EXISTS event_types;
|
||||
ALTER TABLE message_notifications DROP COLUMN IF EXISTS event_types;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS step_details;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS renew_method;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS duration_ms;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS request_count;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS response_content;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS step_details;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS renew_method;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS duration_ms;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS request_count;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS response_content;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS updated_cookie_count;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN IF EXISTS step_details;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN IF EXISTS renew_method;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN IF EXISTS duration_ms;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN IF EXISTS request_count;
|
||||
@@ -0,0 +1,63 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE notification_channels ADD COLUMN event_types TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE message_notifications ADD COLUMN event_types TEXT NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN duration_ms INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN request_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN response_content TEXT NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN duration_ms INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN request_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN response_content TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN updated_cookie_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN duration_ms INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN request_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS risk_control_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
cookie_id TEXT NOT NULL,
|
||||
event_type TEXT NOT NULL DEFAULT 'slider_captcha',
|
||||
event_description TEXT NOT NULL DEFAULT '',
|
||||
processing_result TEXT NOT NULL DEFAULT '',
|
||||
processing_status TEXT NOT NULL DEFAULT 'processing',
|
||||
captcha_engine TEXT NOT NULL DEFAULT '',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
duration_ms INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
INSERT OR IGNORE INTO system_settings (key, value, description) VALUES
|
||||
('log_level', 'info', '日志输出等级:debug/info/warn/error'),
|
||||
('log_format', 'text', '日志输出格式:text/json'),
|
||||
('renewal_log_retention_days', '10', '续期日志保留天数');
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS risk_control_logs;
|
||||
DELETE FROM system_settings WHERE key IN ('log_level', 'log_format', 'renewal_log_retention_days');
|
||||
|
||||
ALTER TABLE notification_channels DROP COLUMN event_types;
|
||||
ALTER TABLE message_notifications DROP COLUMN event_types;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN step_details;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN renew_method;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN duration_ms;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN request_count;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN response_content;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN step_details;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN renew_method;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN duration_ms;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN request_count;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN response_content;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN updated_cookie_count;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN step_details;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN renew_method;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN duration_ms;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN request_count;
|
||||
@@ -61,3 +61,16 @@ type AccountLoginLog struct {
|
||||
DurationMS int64
|
||||
CreatedAt int64
|
||||
}
|
||||
|
||||
// RiskControlLog 记录滑块/人脸/风控恢复过程。
|
||||
type RiskControlLog struct {
|
||||
ID int64
|
||||
CookieID string
|
||||
EventType string
|
||||
EventDescription string
|
||||
ProcessingResult string
|
||||
ProcessingStatus string
|
||||
CaptchaEngine string
|
||||
ErrorMessage string
|
||||
DurationMS int64
|
||||
}
|
||||
@@ -444,6 +444,47 @@ func TestMultiDB_Notifications(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiDB_Migration14DownUp(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
t.Run(tg.name, func(t *testing.T) {
|
||||
defer tg.cleanup()
|
||||
subdir, gooseDialect := migrationTestSubdir(t, tg.dialect)
|
||||
if err := goose.SetDialect(gooseDialect); err != nil {
|
||||
t.Fatalf("set goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration 14 down: %v", err)
|
||||
}
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "notification_channels", "event_types") {
|
||||
t.Fatal("notification_channels.event_types should be removed after down")
|
||||
}
|
||||
if tableExistsForDialect(t, tg.store.DB, tg.dialect, "risk_control_logs") {
|
||||
t.Fatal("risk_control_logs should be removed after down")
|
||||
}
|
||||
|
||||
if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration up after down: %v", err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
table string
|
||||
col string
|
||||
}{
|
||||
{"notification_channels", "event_types"},
|
||||
{"message_notifications", "event_types"},
|
||||
{"scheduled_cookies_refresh_log", "step_details"},
|
||||
{"scheduled_login_renew_log", "updated_cookie_count"},
|
||||
{"scheduled_api_cookie_renew_log", "request_count"},
|
||||
{"risk_control_logs", "processing_status"},
|
||||
} {
|
||||
if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_CardsCreateGet 验证 cards Create + Get 的 NULL 列扫描(含 nullable 字段)。
|
||||
func TestMultiDB_CardsCreateGet(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
@@ -482,4 +523,83 @@ func TestMultiDB_CardsCreateGet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func migrationTestSubdir(t *testing.T, dialect Dialect) (string, string) {
|
||||
t.Helper()
|
||||
switch dialect {
|
||||
case DialectSQLite:
|
||||
return "sqlite", "sqlite3"
|
||||
case DialectMySQL:
|
||||
return "mysql", "mysql"
|
||||
case DialectPostgres:
|
||||
return "postgres", "postgres"
|
||||
default:
|
||||
t.Fatalf("unknown dialect: %s", dialect)
|
||||
return "", ""
|
||||
}
|
||||
}
|
||||
|
||||
func columnExistsForDialect(t *testing.T, db *sql.DB, dialect Dialect, table, col string) bool {
|
||||
t.Helper()
|
||||
var query string
|
||||
var args []any
|
||||
switch dialect {
|
||||
case DialectSQLite:
|
||||
rows, err := db.Query(`SELECT name FROM pragma_table_info(?)`, table)
|
||||
if err != nil {
|
||||
t.Fatalf("pragma_table_info(%s): %v", table, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
t.Fatalf("scan column name: %v", err)
|
||||
}
|
||||
if name == col {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("column rows: %v", err)
|
||||
}
|
||||
return false
|
||||
case DialectMySQL:
|
||||
query = `SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?`
|
||||
args = []any{table, col}
|
||||
case DialectPostgres:
|
||||
query = `SELECT COUNT(*) FROM information_schema.columns WHERE table_schema='public' AND table_name=? AND column_name=?`
|
||||
args = []any{table, col}
|
||||
default:
|
||||
t.Fatalf("unknown dialect: %s", dialect)
|
||||
}
|
||||
var count int
|
||||
if err := db.QueryRow(query, args...).Scan(&count); err != nil {
|
||||
t.Fatalf("column exists query %s.%s: %v", table, col, err)
|
||||
}
|
||||
return count > 0
|
||||
}
|
||||
|
||||
func tableExistsForDialect(t *testing.T, db *sql.DB, dialect Dialect, table string) bool {
|
||||
t.Helper()
|
||||
var query string
|
||||
var args []any
|
||||
switch dialect {
|
||||
case DialectSQLite:
|
||||
query = `SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?`
|
||||
args = []any{table}
|
||||
case DialectMySQL:
|
||||
query = `SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?`
|
||||
args = []any{table}
|
||||
case DialectPostgres:
|
||||
query = `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name=?`
|
||||
args = []any{table}
|
||||
default:
|
||||
t.Fatalf("unknown dialect: %s", dialect)
|
||||
}
|
||||
var count int
|
||||
if err := db.QueryRow(query, args...).Scan(&count); err != nil {
|
||||
t.Fatalf("table exists query %s: %v", table, err)
|
||||
}
|
||||
return count > 0
|
||||
}
|
||||
|
||||
func boolPtr(b bool) *bool { return &b }
|
||||
@@ -7,10 +7,11 @@ import (
|
||||
|
||||
// NotificationChannel 通知渠道(含配置 JSON)。
|
||||
type NotificationChannel struct {
|
||||
ID int64
|
||||
Name string
|
||||
Type string
|
||||
Config string // JSON
|
||||
ID int64
|
||||
Name string
|
||||
Type string
|
||||
Config string // JSON
|
||||
EventTypes string // JSON array or comma-separated event codes
|
||||
}
|
||||
|
||||
// Notifications 通知绑定操作。
|
||||
@@ -23,7 +24,8 @@ type Notifications struct {
|
||||
// 移植自 get_account_notifications。
|
||||
func (n *Notifications) AccountChannels(ctx context.Context, cookieID string) ([]NotificationChannel, error) {
|
||||
rows, err := n.DB.QueryContext(ctx,
|
||||
`SELECT nc.id, nc.name, nc.type, nc.config
|
||||
`SELECT nc.id, nc.name, nc.type, nc.config,
|
||||
COALESCE(NULLIF(mn.event_types,''), nc.event_types, '')
|
||||
FROM message_notifications mn
|
||||
JOIN cookies c ON c.id=mn.cookie_id
|
||||
JOIN notification_channels nc ON mn.channel_id = nc.id AND nc.user_id=c.user_id
|
||||
@@ -36,7 +38,7 @@ func (n *Notifications) AccountChannels(ctx context.Context, cookieID string) ([
|
||||
var out []NotificationChannel
|
||||
for rows.Next() {
|
||||
var c NotificationChannel
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config); err != nil {
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
|
||||
+41
-9
@@ -43,6 +43,10 @@ type RenewalLog struct {
|
||||
UpdatedCookieNames []string
|
||||
UpdatedCookieCount int
|
||||
ResponseContent string
|
||||
StepDetails string
|
||||
RenewMethod string
|
||||
DurationMS int64
|
||||
RequestCount int
|
||||
NextExpireAt int64
|
||||
}
|
||||
|
||||
@@ -170,21 +174,29 @@ func (r *RenewalStore) AddBrowserCookieRenewLog(ctx context.Context, log Renewal
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`INSERT INTO scheduled_cookies_refresh_log
|
||||
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
||||
updated_cookie_count, next_expire_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
updated_cookie_count, next_expire_at, step_details, renew_method, duration_ms,
|
||||
request_count, response_content, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.NextExpireAt)
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.NextExpireAt,
|
||||
log.StepDetails, log.RenewMethod, log.DurationMS, log.RequestCount, log.ResponseContent)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddLoginRenewLog 记录 login_renew 任务日志。
|
||||
func (r *RenewalStore) AddLoginRenewLog(ctx context.Context, log RenewalLog) error {
|
||||
if log.UpdatedCookieCount == 0 {
|
||||
log.UpdatedCookieCount = len(log.UpdatedCookieNames)
|
||||
}
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`INSERT INTO scheduled_login_renew_log
|
||||
(batch_id, cookie_id, status, message, error_message, updated_cookie_names, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
||||
updated_cookie_count, step_details, renew_method, duration_ms, request_count,
|
||||
response_content, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
||||
strings.Join(log.UpdatedCookieNames, ","))
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.StepDetails,
|
||||
log.RenewMethod, log.DurationMS, log.RequestCount, log.ResponseContent)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -196,13 +208,33 @@ func (r *RenewalStore) AddAPICookieRenewLog(ctx context.Context, log RenewalLog)
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`INSERT INTO scheduled_api_cookie_renew_log
|
||||
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
||||
updated_cookie_count, response_content, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
updated_cookie_count, response_content, step_details, renew_method, duration_ms,
|
||||
request_count, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.ResponseContent)
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.ResponseContent,
|
||||
log.StepDetails, log.RenewMethod, log.DurationMS, log.RequestCount)
|
||||
return err
|
||||
}
|
||||
|
||||
// CleanupLogs deletes renewal logs older than retentionDays. Non-positive values skip cleanup.
|
||||
func (r *RenewalStore) CleanupLogs(ctx context.Context, retentionDays int) error {
|
||||
if retentionDays <= 0 {
|
||||
return nil
|
||||
}
|
||||
cutoff := time.Now().AddDate(0, 0, -retentionDays)
|
||||
for _, table := range []string{
|
||||
"scheduled_cookies_refresh_log",
|
||||
"scheduled_login_renew_log",
|
||||
"scheduled_api_cookie_renew_log",
|
||||
} {
|
||||
if _, err := r.DB.ExecContext(ctx, `DELETE FROM `+table+` WHERE created_at < ?`, cutoff); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecentBrowserCookieRenewStatuses 返回最近 limit 条浏览器续期日志状态。
|
||||
func (r *RenewalStore) RecentBrowserCookieRenewStatuses(ctx context.Context, cookieID string, limit int) ([]string, error) {
|
||||
if limit <= 0 {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// RiskControlLogs 写入风控处理日志。
|
||||
type RiskControlLogs struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
}
|
||||
|
||||
// Add 新增一条风控日志,返回自增 ID。
|
||||
func (r *RiskControlLogs) Add(ctx context.Context, log RiskControlLog) (int64, error) {
|
||||
if log.EventType == "" {
|
||||
log.EventType = "slider_captcha"
|
||||
}
|
||||
if log.ProcessingStatus == "" {
|
||||
log.ProcessingStatus = "processing"
|
||||
}
|
||||
return insertReturningID(ctx, r.DB, r.Dialect,
|
||||
`INSERT INTO risk_control_logs
|
||||
(cookie_id, event_type, event_description, processing_result,
|
||||
processing_status, captcha_engine, error_message, duration_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
log.CookieID, log.EventType, log.EventDescription, log.ProcessingResult,
|
||||
log.ProcessingStatus, log.CaptchaEngine, log.ErrorMessage, log.DurationMS)
|
||||
}
|
||||
|
||||
// Update 更新风控日志处理结果。ID 为 0 时安全跳过。
|
||||
func (r *RiskControlLogs) Update(ctx context.Context, id int64, log RiskControlLog) error {
|
||||
if id == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`UPDATE risk_control_logs
|
||||
SET processing_result=?, processing_status=?, captcha_engine=?,
|
||||
error_message=?, duration_ms=?, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`,
|
||||
log.ProcessingResult, log.ProcessingStatus, log.CaptchaEngine,
|
||||
log.ErrorMessage, log.DurationMS, id)
|
||||
return err
|
||||
}
|
||||
@@ -24,6 +24,7 @@ type Store struct {
|
||||
Tokens *AccountTokens
|
||||
Renewal *RenewalStore
|
||||
LoginLogs *AccountLoginLogs
|
||||
RiskLogs *RiskControlLogs
|
||||
}
|
||||
|
||||
// NewStore 基于 *sql.DB 构造聚合 store。dialect 用于业务 SQL 方言分支。
|
||||
@@ -49,5 +50,6 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
Tokens: &AccountTokens{DB: db, Dialect: dialect},
|
||||
Renewal: &RenewalStore{DB: db, Dialect: dialect},
|
||||
LoginLogs: &AccountLoginLogs{DB: db},
|
||||
RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
|
||||
}
|
||||
}
|
||||
+122
-11
@@ -8,6 +8,7 @@ package engine
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
@@ -25,12 +26,13 @@ import (
|
||||
|
||||
// 账号运行时参数。
|
||||
const (
|
||||
MaxConnectionFailures = 5 // 连续失败上限,触发密码登录刷新
|
||||
MessageSemaphoreSize = 100 // 并发消息处理上限
|
||||
MessageDebounceDelay = 1 * time.Second // 防抖延迟:用户停止发送 1s 后回复
|
||||
MessageExpireTime = time.Hour // 去重有效期
|
||||
ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理
|
||||
HeartbeatInterval = 15 * time.Second
|
||||
MaxConnectionFailures = 5 // 连续失败上限,触发密码登录刷新
|
||||
TokenFetchDisableThreshold = 20 // 连续获取 token 失败达到阈值后禁用账号
|
||||
MessageSemaphoreSize = 100 // 并发消息处理上限
|
||||
MessageDebounceDelay = 1 * time.Second // 防抖延迟:用户停止发送 1s 后回复
|
||||
MessageExpireTime = time.Hour // 去重有效期
|
||||
ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理
|
||||
HeartbeatInterval = 15 * time.Second
|
||||
// token_refresh_loop 与对方项目一致,默认 20 小时一次;在线保活主要由
|
||||
// cookieRefreshLoop 负责,每 180 秒刷新一次 Cookie/token。
|
||||
TokenRefreshInterval = 20 * time.Hour
|
||||
@@ -59,6 +61,15 @@ const (
|
||||
AlertLevelCritical = "critical"
|
||||
)
|
||||
|
||||
const (
|
||||
EventAccountOffline = "account_offline"
|
||||
EventAccountRecovered = "account_recovered"
|
||||
EventAccountDisabled = "account_disabled"
|
||||
EventSecurityVerification = "security_verification"
|
||||
EventTokenRenewal = "token_renewal"
|
||||
EventSystemError = "system_error"
|
||||
)
|
||||
|
||||
// Handler 是业务逻辑注入点(Phase 3 实现)。
|
||||
// 收到一条防抖后的聊天消息时回调;返回错误仅记录日志、不影响主循环。
|
||||
// 注:生产 handlerAdapter.HandleChatMessage 当前为 no-op,留作未来注入聊天旁路处理
|
||||
@@ -75,6 +86,14 @@ type Handler interface {
|
||||
OnAccountAlert(ctx context.Context, cookieID, level, title, body string)
|
||||
}
|
||||
|
||||
type accountEventHandler interface {
|
||||
OnAccountEvent(ctx context.Context, cookieID, eventType, level, title, body string)
|
||||
}
|
||||
|
||||
type tokenCaptchaHandler interface {
|
||||
OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL string) (newCookies string, ok bool)
|
||||
}
|
||||
|
||||
// ChatMessage 防抖后投递给业务层的一条聊天消息。
|
||||
type ChatMessage struct {
|
||||
AccountID string // cookie_id
|
||||
@@ -138,6 +157,10 @@ type Account struct {
|
||||
conn WSConn
|
||||
connStartedAt time.Time // 本次 WS 连接建立时间,用于短连接检测
|
||||
authExpiredAlerted bool // 已发过 auth_expired 告警,连接恢复后复位(避免刷屏)
|
||||
offlineNotified bool
|
||||
offlineSince time.Time
|
||||
lastOfflineReason string
|
||||
tokenFetchFailures int
|
||||
|
||||
// 去重
|
||||
dedupMu sync.Mutex
|
||||
@@ -281,13 +304,20 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.logger.Error("获取 token 失败", "err", err)
|
||||
a.mu.Lock()
|
||||
a.connFailures++
|
||||
a.tokenFetchFailures++
|
||||
failures := a.connFailures
|
||||
tokenFailures := a.tokenFetchFailures
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeError(ctx, err)
|
||||
if tokenFailures >= TokenFetchDisableThreshold {
|
||||
reason := fmt.Sprintf("连续 %d 次获取 token 失败,最后错误:%s", TokenFetchDisableThreshold, errString(err))
|
||||
a.disableForTokenFailures(ctx, reason)
|
||||
return nil
|
||||
}
|
||||
if mtop.IsRiskVerificationErr(err) {
|
||||
a.logger.Warn("闲鱼要求安全验证,停止快速重试", "err", err)
|
||||
a.clearTokenCache(ctx)
|
||||
a.alert(ctx, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
"账号触发闲鱼风控验证(滑块/人脸等)。系统已停止快速重试,请在后台重新扫码或完成验证。")
|
||||
if sleepCtx(ctx, AuthExpiredRetryInterval) != nil {
|
||||
return ctx.Err()
|
||||
@@ -297,13 +327,14 @@ func (a *Account) Run(parent context.Context) error {
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
a.logger.Warn("session 已失效,先做轻量登录态检查与接口续期", "err", err)
|
||||
a.clearTokenCache(ctx)
|
||||
a.notifyOffline(ctx, "token/session 已失效:"+errString(err))
|
||||
statusCheck := a.tryLoginStatusCheck(ctx)
|
||||
if statusCheck.riskRequired {
|
||||
body := "loginuser.get 返回风控验证要求,请在后台重新扫码或完成验证。"
|
||||
if statusCheck.verificationURL != "" {
|
||||
body += "验证地址:" + statusCheck.verificationURL
|
||||
}
|
||||
a.alert(ctx, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
body)
|
||||
if sleepCtx(ctx, AuthExpiredRetryInterval) != nil {
|
||||
return ctx.Err()
|
||||
@@ -324,7 +355,7 @@ func (a *Account) Run(parent context.Context) error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
a.alert(ctx, AlertLevelWarn, "账号 session 已失效",
|
||||
a.alertEvent(ctx, EventAccountOffline, AlertLevelWarn, "账号 session 已失效",
|
||||
"登录凭证已被闲鱼服务端判定为失效,接口续期未恢复,系统将继续尝试浏览器密码登录自动恢复。")
|
||||
if err := a.handleMaxFailures(ctx); err != nil {
|
||||
return err
|
||||
@@ -346,6 +377,7 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.currentToken = token
|
||||
a.CookieStr = cookieStr
|
||||
a.connFailures = 0
|
||||
a.tokenFetchFailures = 0
|
||||
a.mu.Unlock()
|
||||
a.logger.Info("token 刷新成功")
|
||||
a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务")
|
||||
@@ -398,8 +430,17 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.conn = conn
|
||||
a.connStartedAt = time.Now()
|
||||
a.authExpiredAlerted = false // 连接成功,复位 auth_expired 告警标记
|
||||
shouldRecovered := a.offlineNotified
|
||||
offlineSince := a.offlineSince
|
||||
a.offlineNotified = false
|
||||
a.offlineSince = time.Time{}
|
||||
a.lastOfflineReason = ""
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
|
||||
if shouldRecovered {
|
||||
a.alertEvent(ctx, EventAccountRecovered, AlertLevelInfo, "账号已恢复在线",
|
||||
fmt.Sprintf("账号 %s 已重新连接闲鱼消息服务。掉线开始时间:%s。", a.CookieID, formatTimeOrUnknown(offlineSince)))
|
||||
}
|
||||
|
||||
// 3) 心跳 + 消息接收,并并行运行 token/cookie 定时刷新。
|
||||
hbCtx, hbCancel := context.WithCancel(ctx)
|
||||
@@ -483,6 +524,7 @@ func (a *Account) Stop() {
|
||||
// handleMaxFailures 连续失败达上限:尝试密码登录刷新;失败则返回 err 触发上层重启实例。
|
||||
func (a *Account) handleMaxFailures(ctx context.Context) error {
|
||||
a.logger.Warn("连续失败达上限,触发密码登录刷新", "failures", MaxConnectionFailures)
|
||||
a.notifyOffline(ctx, fmt.Sprintf("消息服务连续认证/连接失败 %d 次,开始自动恢复", MaxConnectionFailures))
|
||||
a.mu.Lock()
|
||||
lastMsg := a.lastMsgReceived
|
||||
lastLogin := a.lastPasswordLogin
|
||||
@@ -517,7 +559,7 @@ func (a *Account) handleMaxFailures(ctx context.Context) error {
|
||||
// 后,Run 顶部的 reloadCookieFromDB 会吸收新 cookie 并自愈回在线。
|
||||
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,自动慢重试中,重新扫码后自愈")
|
||||
if a.markAuthExpired() {
|
||||
a.alert(ctx, AlertLevelCritical, "账号自动恢复失败,需人工处理",
|
||||
a.alertEvent(ctx, EventAccountOffline, AlertLevelCritical, "账号自动恢复失败,需人工处理",
|
||||
fmt.Sprintf("账号 %s 连续失败 %d 次,登录凭证暂未自动恢复。账号将每 %v 慢重试一次,不会停止运行;前往后台重新扫码后无需手动重启即可自动恢复在线。", a.CookieID, MaxConnectionFailures, AuthExpiredRetryInterval))
|
||||
}
|
||||
if err := sleepCtx(ctx, AuthExpiredRetryInterval); err != nil {
|
||||
@@ -538,11 +580,45 @@ func (a *Account) markAuthExpired() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *Account) notifyOffline(ctx context.Context, reason string) {
|
||||
a.mu.Lock()
|
||||
if a.offlineNotified {
|
||||
a.mu.Unlock()
|
||||
return
|
||||
}
|
||||
a.offlineNotified = true
|
||||
a.offlineSince = time.Now()
|
||||
a.lastOfflineReason = reason
|
||||
a.mu.Unlock()
|
||||
a.alertEvent(ctx, EventAccountOffline, AlertLevelWarn, "账号已掉线,正在自动恢复",
|
||||
fmt.Sprintf("账号 %s 出现登录凭证过期或认证掉线。原因:%s。系统会先发送本通知,再继续尝试轻量续期、浏览器续期或密码登录恢复。", a.CookieID, reason))
|
||||
}
|
||||
|
||||
func (a *Account) disableForTokenFailures(ctx context.Context, reason string) {
|
||||
a.logger.Error("连续获取 token 失败,自动禁用账号", "account", a.CookieID, "reason", reason)
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
if err := a.store.Cookies.SetStatusWithReason(ctx, a.CookieID, false, reason); err != nil {
|
||||
a.logger.Error("自动禁用账号失败", "account", a.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeStopped, "连续获取 token 失败,账号已自动禁用")
|
||||
a.alertEvent(ctx, EventAccountDisabled, AlertLevelCritical, "账号已自动禁用", reason)
|
||||
}
|
||||
|
||||
// alert 触发账号告警通知。handler 未注入或为 nil 时静默跳过。
|
||||
func (a *Account) alert(ctx context.Context, level, title, body string) {
|
||||
a.alertEvent(ctx, EventTokenRenewal, level, title, body)
|
||||
}
|
||||
|
||||
func (a *Account) alertEvent(ctx context.Context, eventType, level, title, body string) {
|
||||
if a.handler == nil {
|
||||
return
|
||||
}
|
||||
if h, ok := a.handler.(accountEventHandler); ok {
|
||||
h.OnAccountEvent(ctx, a.CookieID, eventType, level, title, body)
|
||||
return
|
||||
}
|
||||
a.handler.OnAccountAlert(ctx, a.CookieID, level, title, body)
|
||||
}
|
||||
|
||||
@@ -552,6 +628,13 @@ func (a *Account) resetFailures() {
|
||||
a.connFailures = 0
|
||||
}
|
||||
|
||||
func formatTimeOrUnknown(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return "未知"
|
||||
}
|
||||
return t.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
// tryLoginStatusCheck 调用 mtop.taobao.idlemessage.pc.loginuser.get 做轻量登录态确认。
|
||||
// 这个接口的成本低于完整 token 刷新和浏览器动作,且可能顺手下发新的签名 Cookie;
|
||||
// 因此在 session 失效后、接口续期前先跑一遍,避免已实现的登录态检查能力闲置。
|
||||
@@ -730,6 +813,12 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
|
||||
}
|
||||
}
|
||||
res, err := a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
|
||||
if err != nil && mtop.IsRiskVerificationErr(err) {
|
||||
if recoveredCookies, ok := a.tryTokenCaptchaRecovery(ctx, cookieStr, err); ok {
|
||||
cookieStr = recoveredCookies
|
||||
res, err = a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
|
||||
}
|
||||
}
|
||||
if res != nil && res.UpdatedCookies != "" && res.UpdatedCookies != cookieStr {
|
||||
a.replaceCookieStr(res.UpdatedCookies)
|
||||
cookieStr = res.UpdatedCookies
|
||||
@@ -750,10 +839,32 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
|
||||
a.saveTokenCache(ctx, deviceID, res.AccessToken)
|
||||
a.mu.Lock()
|
||||
a.lastMsgReceived = time.Time{}
|
||||
a.tokenFetchFailures = 0
|
||||
a.mu.Unlock()
|
||||
return res.AccessToken, cookieStr, nil
|
||||
}
|
||||
|
||||
func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr string, err error) (string, bool) {
|
||||
h, ok := a.handler.(tokenCaptchaHandler)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
var riskErr *mtop.RiskVerificationError
|
||||
if !errors.As(err, &riskErr) || strings.TrimSpace(riskErr.VerificationURL) == "" {
|
||||
return "", false
|
||||
}
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求滑块验证",
|
||||
"token 刷新触发闲鱼风控验证,系统将尝试自动完成滑块并合并 x5sec。")
|
||||
newCookies, ok := h.OnTokenCaptchaVerification(ctx, a.CookieID, cookieStr, riskErr.VerificationURL)
|
||||
if !ok || strings.TrimSpace(newCookies) == "" {
|
||||
return "", false
|
||||
}
|
||||
a.replaceCookieStr(newCookies)
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeConnecting, "token 风控验证已处理,正在重新获取登录凭证")
|
||||
return newCookies, true
|
||||
}
|
||||
|
||||
// acquireToken 取用于 WS /reg 的 accessToken:缓存命中且未过期则跳过 mtop(降低风控
|
||||
// 与瞬时失败影响),否则调 refreshToken 重新派生并落库缓存。
|
||||
//
|
||||
@@ -989,7 +1100,7 @@ func (a *Account) setRuntimeError(ctx context.Context, err error) {
|
||||
a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证,请重新扫码并完成验证")
|
||||
// 仅在从非验证状态转入时告警一次,避免重复刷屏。
|
||||
if prev != RuntimeVerificationRequired {
|
||||
a.alert(ctx, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
"账号触发闲鱼风控验证(滑块/短信/人脸等)。系统可能无法自动恢复,请前往后台扫码完成验证。")
|
||||
}
|
||||
case strings.Contains(msg, "登录凭证已失效"), strings.Contains(msg, "fail_sys_token_exoired"), strings.Contains(msg, "fail_sys_token_expired"), strings.Contains(msg, "cookie 缺少 unb"):
|
||||
|
||||
@@ -260,6 +260,24 @@ func TestResetFailures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshTokenSuccessResetsTokenFetchFailures(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
acc.mtop = &fakeRunMtop{token: "tok-reset"}
|
||||
acc.tokenFetchFailures = 19
|
||||
|
||||
token, _, err := acc.refreshToken(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("refreshToken: %v", err)
|
||||
}
|
||||
if token != "tok-reset" {
|
||||
t.Fatalf("token=%q want tok-reset", token)
|
||||
}
|
||||
if acc.tokenFetchFailures != 0 {
|
||||
t.Fatalf("tokenFetchFailures=%d want 0", acc.tokenFetchFailures)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryDelay_FailureClampsAtOne connFailures=0 时按 1 计算。
|
||||
func TestRetryDelay_FailureClampsAtOne(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
@@ -395,6 +413,7 @@ func TestHandleMaxFailures_PasswordLoginSuccess(t *testing.T) {
|
||||
// failingRefreshHandler OnPasswordLoginRefresh 返回 false 的 handler,记录告警。
|
||||
type failingRefreshHandler struct {
|
||||
alerts []string
|
||||
events []string
|
||||
}
|
||||
|
||||
func (f *failingRefreshHandler) HandleChatMessage(context.Context, ChatMessage) error { return nil }
|
||||
@@ -405,6 +424,10 @@ func (f *failingRefreshHandler) OnPasswordLoginRefresh(context.Context, string)
|
||||
func (f *failingRefreshHandler) OnAccountAlert(_ context.Context, _, level, _, _ string) {
|
||||
f.alerts = append(f.alerts, level)
|
||||
}
|
||||
func (f *failingRefreshHandler) OnAccountEvent(_ context.Context, _, eventType, level, _, _ string) {
|
||||
f.events = append(f.events, eventType)
|
||||
f.alerts = append(f.alerts, level)
|
||||
}
|
||||
|
||||
// TestHandleMaxFailures_PasswordLoginFailure 密码登录刷新失败:不再硬退出,进入慢重试,
|
||||
// 状态 AuthExpired,触发一次 critical 告警。
|
||||
@@ -433,8 +456,11 @@ func TestHandleMaxFailures_PasswordLoginFailure(t *testing.T) {
|
||||
if s := acc.RuntimeStatus(); s.State != RuntimeAuthExpired {
|
||||
t.Errorf("状态应为 auth_expired,got %q", s.State)
|
||||
}
|
||||
if len(h.alerts) != 1 || h.alerts[0] != AlertLevelCritical {
|
||||
t.Errorf("应触发一次 critical 告警,got %+v", h.alerts)
|
||||
if len(h.alerts) != 2 || h.alerts[0] != AlertLevelWarn || h.alerts[1] != AlertLevelCritical {
|
||||
t.Errorf("应先触发掉线 warn,再触发恢复失败 critical,got %+v", h.alerts)
|
||||
}
|
||||
if len(h.events) != 2 || h.events[0] != EventAccountOffline || h.events[1] != EventAccountOffline {
|
||||
t.Errorf("事件类型应为账号掉线通知,got %+v", h.events)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -212,7 +212,7 @@ func TestHandleMaxFailures_AlertOnce(t *testing.T) {
|
||||
}
|
||||
call()
|
||||
call()
|
||||
if len(h.alerts) != 1 || h.alerts[0] != AlertLevelCritical {
|
||||
t.Fatalf("两次 handleMaxFailures 应只告警一次,got %+v", h.alerts)
|
||||
if len(h.alerts) != 2 || h.alerts[0] != AlertLevelWarn || h.alerts[1] != AlertLevelCritical {
|
||||
t.Fatalf("两次 handleMaxFailures 应只发一次掉线 warn 和一次恢复失败 critical,got %+v", h.alerts)
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,27 @@ func (f *fakeRunMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ strin
|
||||
return &mtop.RefreshResult{AccessToken: f.token}, nil
|
||||
}
|
||||
|
||||
type fakeFailTokenMtop struct{ err error }
|
||||
|
||||
func (f *fakeFailTokenMtop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeFailTokenMtop) ConsignContext(context.Context, string, string) (bool, []string, string, error) {
|
||||
return true, nil, "", nil
|
||||
}
|
||||
func (f *fakeFailTokenMtop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeFailTokenMtop) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeFailTokenMtop) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeFailTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) {
|
||||
return nil, f.err
|
||||
}
|
||||
|
||||
// fakeWSConn 实现 WSConn,可控地投递消息并阻塞到 ctx 取消。
|
||||
type fakeWSConn struct {
|
||||
mu sync.Mutex
|
||||
@@ -97,11 +118,11 @@ func (f *fakeWSConn) SendImage(_ context.Context, _, _, _, url string, _, _ int)
|
||||
|
||||
// fakeDialer 按预设序列返回连接或错误,第 N 次(1-based)调用返回 dialResults[N-1]。
|
||||
type fakeDialer struct {
|
||||
mu sync.Mutex
|
||||
results []dialResult // 每次.Dial 的结果
|
||||
calls int
|
||||
conns []*fakeWSConn
|
||||
lastCfg ws.Config // 记录最后一次 Dial 的配置(含 AccessToken)
|
||||
mu sync.Mutex
|
||||
results []dialResult // 每次.Dial 的结果
|
||||
calls int
|
||||
conns []*fakeWSConn
|
||||
lastCfg ws.Config // 记录最后一次 Dial 的配置(含 AccessToken)
|
||||
}
|
||||
|
||||
type dialResult struct {
|
||||
@@ -330,6 +351,33 @@ func TestRun_DisabledAccountExits(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
|
||||
defer cleanup()
|
||||
h := &failingRefreshHandler{}
|
||||
acc.handler = h
|
||||
acc.mu.Lock()
|
||||
acc.tokenFetchFailures = TokenFetchDisableThreshold - 1
|
||||
acc.mu.Unlock()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(context.Background()) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("threshold disable should exit nil, got %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("token failure threshold should disable without retry sleep")
|
||||
}
|
||||
if store.Cookies.GetStatus(context.Background(), "cid") {
|
||||
t.Fatal("token failure threshold should disable account")
|
||||
}
|
||||
if len(h.events) == 0 || h.events[len(h.events)-1] != EventAccountDisabled {
|
||||
t.Fatalf("disable event not emitted: events=%+v alerts=%+v", h.events, h.alerts)
|
||||
}
|
||||
}
|
||||
|
||||
var errFakeDial = fakeDialErr{}
|
||||
|
||||
type fakeDialErr struct{}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Level is the process-wide dynamic slog level.
|
||||
var Level slog.LevelVar
|
||||
|
||||
func init() {
|
||||
Level.Set(slog.LevelInfo)
|
||||
}
|
||||
|
||||
// NewLogger creates a slog logger wired to the dynamic Level.
|
||||
func NewLogger(w io.Writer, format string) *slog.Logger {
|
||||
opts := &slog.HandlerOptions{Level: &Level}
|
||||
if strings.EqualFold(strings.TrimSpace(format), "json") {
|
||||
return slog.New(slog.NewJSONHandler(w, opts))
|
||||
}
|
||||
return slog.New(slog.NewTextHandler(w, opts))
|
||||
}
|
||||
|
||||
// SetLevel updates the process-wide log level.
|
||||
func SetLevel(raw string) error {
|
||||
lv, err := ParseLevel(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
Level.Set(lv)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseLevel parses debug/info/warn/error.
|
||||
func ParseLevel(raw string) (slog.Level, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "", "info":
|
||||
return slog.LevelInfo, nil
|
||||
case "debug":
|
||||
return slog.LevelDebug, nil
|
||||
case "warn", "warning":
|
||||
return slog.LevelWarn, nil
|
||||
case "error":
|
||||
return slog.LevelError, nil
|
||||
default:
|
||||
return slog.LevelInfo, fmt.Errorf("无效日志等级: %s", raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseLevelAndSetLevel(t *testing.T) {
|
||||
defer Level.Set(slog.LevelInfo)
|
||||
|
||||
cases := map[string]slog.Level{
|
||||
"": slog.LevelInfo,
|
||||
"debug": slog.LevelDebug,
|
||||
"INFO": slog.LevelInfo,
|
||||
"warning": slog.LevelWarn,
|
||||
"error": slog.LevelError,
|
||||
}
|
||||
for in, want := range cases {
|
||||
got, err := ParseLevel(in)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLevel(%q): %v", in, err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("ParseLevel(%q)=%v want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
if _, err := ParseLevel("verbose"); err == nil {
|
||||
t.Fatal("invalid level should fail")
|
||||
}
|
||||
if err := SetLevel("debug"); err != nil {
|
||||
t.Fatalf("SetLevel: %v", err)
|
||||
}
|
||||
if got := Level.Level(); got != slog.LevelDebug {
|
||||
t.Fatalf("global level=%v want debug", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewLoggerHonorsDynamicLevel(t *testing.T) {
|
||||
defer Level.Set(slog.LevelInfo)
|
||||
var buf bytes.Buffer
|
||||
logger := NewLogger(&buf, "text")
|
||||
|
||||
Level.Set(slog.LevelWarn)
|
||||
logger.Info("hidden")
|
||||
logger.Warn("visible")
|
||||
out := buf.String()
|
||||
if strings.Contains(out, "hidden") {
|
||||
t.Fatalf("info log should be filtered: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "visible") {
|
||||
t.Fatalf("warn log should be emitted: %s", out)
|
||||
}
|
||||
}
|
||||
+226
-22
@@ -22,6 +22,27 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
const (
|
||||
EventAccountOffline = "account_offline"
|
||||
EventAccountRecovered = "account_recovered"
|
||||
EventAccountDisabled = "account_disabled"
|
||||
EventSecurityVerification = "security_verification"
|
||||
EventTokenRenewal = "token_renewal"
|
||||
EventDeliveryResult = "delivery_result"
|
||||
EventSystemError = "system_error"
|
||||
)
|
||||
|
||||
// NotificationEvent 是一条可被渠道订阅过滤的通知事件。
|
||||
type NotificationEvent struct {
|
||||
AccountID string
|
||||
Type string
|
||||
Level string
|
||||
Title string
|
||||
Body string
|
||||
Fields map[string]string
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
// Notifier 通知发送器。
|
||||
type Notifier struct {
|
||||
cookieID string
|
||||
@@ -46,35 +67,62 @@ func New(cookieID string, store *db.Store, logger *slog.Logger) *Notifier {
|
||||
// NotifyDelivery 发送发货结果通知。
|
||||
// accountID 为 cookie_id。向该账号所有已启用渠道发送发货通知。
|
||||
func (n *Notifier) NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string) {
|
||||
channels, err := n.store.Notifications.AccountChannels(context.Background(), accountID)
|
||||
if err != nil || len(channels) == 0 {
|
||||
return
|
||||
}
|
||||
// 构造通知文案。
|
||||
body := fmt.Sprintf("🚨 自动发货通知\n\n账号: %s\n买家: %s (ID: %s)\n商品ID: %s\n聊天ID: %s\n结果: %s\n时间: %s\n\n请及时处理!",
|
||||
accountID, buyerName, buyerID, itemID, fallback(chatID, "未知"), message, time.Now().Format("2006-01-02 15:04:05"))
|
||||
for _, ch := range channels {
|
||||
if err := n.send(ch, body); err != nil {
|
||||
n.logger.Error("发送通知失败", "channel", ch.Type, "err", err)
|
||||
}
|
||||
}
|
||||
n.NotifyEvent(context.Background(), NotificationEvent{
|
||||
AccountID: accountID,
|
||||
Type: EventDeliveryResult,
|
||||
Level: "info",
|
||||
Title: "自动发货通知",
|
||||
Body: message,
|
||||
Fields: map[string]string{
|
||||
"买家": fmt.Sprintf("%s (ID: %s)", buyerName, buyerID),
|
||||
"商品ID": itemID,
|
||||
"聊天ID": fallback(chatID, "未知"),
|
||||
"结果": message,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// NotifyAccountAlert 发送账号告警通知(token 失效/自动恢复失败/风控验证等)。
|
||||
// level 取 AlertLevel* 常量。向该账号所有已启用渠道发送。
|
||||
func (n *Notifier) NotifyAccountAlert(accountID, level, title, body string) {
|
||||
n.NotifyAccountEvent(accountID, classifyAccountAlertEvent(title, body), level, title, body)
|
||||
}
|
||||
|
||||
// NotifyAccountEvent 发送指定类型的账号通知。
|
||||
func (n *Notifier) NotifyAccountEvent(accountID, eventType, level, title, body string) {
|
||||
n.NotifyEvent(context.Background(), NotificationEvent{
|
||||
AccountID: accountID,
|
||||
Type: eventType,
|
||||
Level: level,
|
||||
Title: title,
|
||||
Body: body,
|
||||
})
|
||||
}
|
||||
|
||||
// NotifyEvent 根据事件类型筛选渠道并发送通知。
|
||||
func (n *Notifier) NotifyEvent(ctx context.Context, ev NotificationEvent) {
|
||||
if n.store == nil {
|
||||
return
|
||||
}
|
||||
channels, err := n.store.Notifications.AccountChannels(context.Background(), accountID)
|
||||
if ev.Time.IsZero() {
|
||||
ev.Time = time.Now()
|
||||
}
|
||||
channels, err := n.store.Notifications.AccountChannels(ctx, ev.AccountID)
|
||||
if err != nil || len(channels) == 0 {
|
||||
return
|
||||
}
|
||||
full := fmt.Sprintf("🚨 [%s] %s\n\n账号: %s\n时间: %s\n\n%s",
|
||||
levelLabel(level), title, accountID, time.Now().Format("2006-01-02 15:04:05"), body)
|
||||
full := formatEvent(ev)
|
||||
for _, ch := range channels {
|
||||
allowed, err := eventAllowed(ch.EventTypes, ev.Type)
|
||||
if err != nil {
|
||||
n.logger.Warn("通知事件订阅配置无效,跳过渠道", "channel", ch.ID, "event_types", ch.EventTypes, "err", err)
|
||||
continue
|
||||
}
|
||||
if !allowed {
|
||||
continue
|
||||
}
|
||||
if err := n.send(ch, full); err != nil {
|
||||
n.logger.Error("发送告警通知失败", "channel", ch.Type, "err", err)
|
||||
n.logger.Error("发送通知失败", "channel", ch.Type, "event_type", ev.Type, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,6 +155,149 @@ func levelLabel(level string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func eventLabel(eventType string) string {
|
||||
switch eventType {
|
||||
case EventAccountOffline:
|
||||
return "掉线通知"
|
||||
case EventAccountRecovered:
|
||||
return "恢复通知"
|
||||
case EventAccountDisabled:
|
||||
return "禁用通知"
|
||||
case EventSecurityVerification:
|
||||
return "风控验证"
|
||||
case EventTokenRenewal:
|
||||
return "续期通知"
|
||||
case EventDeliveryResult:
|
||||
return "交易通知"
|
||||
case EventSystemError:
|
||||
return "系统错误"
|
||||
default:
|
||||
if eventType == "" {
|
||||
return "通知"
|
||||
}
|
||||
return eventType
|
||||
}
|
||||
}
|
||||
|
||||
func classifyAccountAlertEvent(title, body string) string {
|
||||
msg := strings.ToLower(title + " " + body)
|
||||
switch {
|
||||
case strings.Contains(msg, "风控"), strings.Contains(msg, "验证"),
|
||||
strings.Contains(msg, "滑块"), strings.Contains(msg, "captcha"),
|
||||
strings.Contains(msg, "risk"), strings.Contains(msg, "x5sec"):
|
||||
return EventSecurityVerification
|
||||
case strings.Contains(msg, "禁用"), strings.Contains(msg, "disabled"):
|
||||
return EventAccountDisabled
|
||||
case strings.Contains(msg, "掉线"), strings.Contains(msg, "离线"),
|
||||
strings.Contains(msg, "offline"), strings.Contains(msg, "session"),
|
||||
strings.Contains(msg, "登录凭证已失效"):
|
||||
return EventAccountOffline
|
||||
case strings.Contains(msg, "token"), strings.Contains(msg, "续期"), strings.Contains(msg, "renew"):
|
||||
return EventTokenRenewal
|
||||
default:
|
||||
return EventSystemError
|
||||
}
|
||||
}
|
||||
|
||||
func formatEvent(ev NotificationEvent) string {
|
||||
var b strings.Builder
|
||||
label := eventLabel(ev.Type)
|
||||
level := levelLabel(ev.Level)
|
||||
if level == "" {
|
||||
level = "提示"
|
||||
}
|
||||
title := strings.TrimSpace(ev.Title)
|
||||
if title == "" {
|
||||
title = label
|
||||
}
|
||||
b.WriteString("[")
|
||||
b.WriteString(level)
|
||||
b.WriteString("] ")
|
||||
b.WriteString(title)
|
||||
b.WriteString("\n\n类型: ")
|
||||
b.WriteString(label)
|
||||
if ev.AccountID != "" {
|
||||
b.WriteString("\n账号: ")
|
||||
b.WriteString(ev.AccountID)
|
||||
}
|
||||
b.WriteString("\n时间: ")
|
||||
b.WriteString(ev.Time.Format("2006-01-02 15:04:05"))
|
||||
if len(ev.Fields) > 0 {
|
||||
keys := make([]string, 0, len(ev.Fields))
|
||||
for k := range ev.Fields {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sortStrings(keys)
|
||||
for _, k := range keys {
|
||||
v := strings.TrimSpace(ev.Fields[k])
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
b.WriteByte('\n')
|
||||
b.WriteString(k)
|
||||
b.WriteString(": ")
|
||||
b.WriteString(v)
|
||||
}
|
||||
}
|
||||
body := strings.TrimSpace(ev.Body)
|
||||
if body != "" {
|
||||
b.WriteString("\n\n")
|
||||
b.WriteString(body)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func eventAllowed(raw, eventType string) (bool, error) {
|
||||
eventType = strings.TrimSpace(eventType)
|
||||
if eventType == "" {
|
||||
return true, nil
|
||||
}
|
||||
events, err := parseEventTypes(raw)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if len(events) == 0 {
|
||||
return true, nil
|
||||
}
|
||||
return events[eventType], nil
|
||||
}
|
||||
|
||||
func parseEventTypes(raw string) (map[string]bool, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var arr []string
|
||||
if strings.HasPrefix(raw, "[") {
|
||||
if err := json.Unmarshal([]byte(raw), &arr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
arr = strings.FieldsFunc(raw, func(r rune) bool {
|
||||
return r == ',' || r == ';' || r == ' ' || r == '\n' || r == '\t'
|
||||
})
|
||||
}
|
||||
if len(arr) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
out := make(map[string]bool, len(arr))
|
||||
for _, v := range arr {
|
||||
v = strings.TrimSpace(v)
|
||||
if v != "" {
|
||||
out[v] = true
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func sortStrings(values []string) {
|
||||
for i := 1; i < len(values); i++ {
|
||||
for j := i; j > 0 && values[j-1] > values[j]; j-- {
|
||||
values[j-1], values[j] = values[j], values[j-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Notifier) send(ch db.NotificationChannel, message string) error {
|
||||
cfg := parseConfig(ch.Config)
|
||||
switch ch.Type {
|
||||
@@ -282,14 +473,15 @@ func (n *Notifier) sendTelegram(cfg map[string]any, message string) error {
|
||||
|
||||
// ---- 邮件 ----
|
||||
func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
|
||||
server := strOr(cfg, "smtp_server", "")
|
||||
port := strOr(cfg, "smtp_port", "587")
|
||||
user := strOr(cfg, "smtp_user", "")
|
||||
pass := strOr(cfg, "smtp_password", "")
|
||||
from := strOr(cfg, "smtp_from", "")
|
||||
ctx := context.Background()
|
||||
server := n.configOrSetting(ctx, cfg, "smtp_server", "")
|
||||
port := n.configOrSetting(ctx, cfg, "smtp_port", "587")
|
||||
user := n.configOrSetting(ctx, cfg, "smtp_user", "")
|
||||
pass := n.configOrSetting(ctx, cfg, "smtp_password", "")
|
||||
from := n.configOrSetting(ctx, cfg, "smtp_from", "")
|
||||
to := strOr(cfg, "to_email", strOr(cfg, "email", ""))
|
||||
if server == "" || user == "" || to == "" {
|
||||
return fmt.Errorf("邮件配置不完整")
|
||||
return fmt.Errorf("邮件配置不完整:请配置系统 SMTP 或在邮件渠道中覆盖 SMTP,并填写收件邮箱")
|
||||
}
|
||||
if from == "" {
|
||||
from = user
|
||||
@@ -308,6 +500,18 @@ func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
|
||||
return smtp.SendMail(addr, auth, from, []string{to}, []byte(msg))
|
||||
}
|
||||
|
||||
func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
|
||||
if v := strings.TrimSpace(strOr(cfg, key, "")); v != "" {
|
||||
return v
|
||||
}
|
||||
if n.store != nil && n.store.Settings != nil {
|
||||
if v, err := n.store.Settings.Get(ctx, key); err == nil && strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
|
||||
// postJSON 通用 JSON POST。
|
||||
func (n *Notifier) postJSON(url string, payload any) error {
|
||||
body, err := json.Marshal(payload)
|
||||
|
||||
@@ -2,6 +2,7 @@ package notify
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
@@ -346,9 +347,9 @@ func TestSendWebhook_CustomHeadersAndMethod(t *testing.T) {
|
||||
defer srv.Close()
|
||||
n := New("cid", nil, nil)
|
||||
cfg := map[string]any{
|
||||
"webhook_url": srv.URL,
|
||||
"http_method": "get",
|
||||
"headers": `{"Authorization":"Bearer abc","X-Custom":"v"}`,
|
||||
"webhook_url": srv.URL,
|
||||
"http_method": "get",
|
||||
"headers": `{"Authorization":"Bearer abc","X-Custom":"v"}`,
|
||||
}
|
||||
if err := n.sendWebhook(cfg, "消息"); err != nil {
|
||||
t.Fatalf("sendWebhook: %v", err)
|
||||
@@ -504,13 +505,40 @@ func TestSendEmail_DefaultFrom(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendEmail_UsesSystemSMTPFallback(t *testing.T) {
|
||||
addr, received := fakeSMTPServer(t)
|
||||
host, port, _ := strings.Cut(addr, ":")
|
||||
store, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
for key, value := range map[string]string{
|
||||
"smtp_server": host,
|
||||
"smtp_port": port,
|
||||
"smtp_user": "system@e.com",
|
||||
"smtp_password": "pw",
|
||||
} {
|
||||
if err := store.Settings.Set(ctx, key, value); err != nil {
|
||||
t.Fatalf("set %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
n := New("cid", store, nil)
|
||||
if err := n.sendEmail(map[string]any{"to_email": "to@e.com"}, "系统SMTP正文"); err != nil {
|
||||
t.Fatalf("sendEmail with system fallback: %v", err)
|
||||
}
|
||||
body := received.String()
|
||||
if !strings.Contains(body, "From: system@e.com") || !strings.Contains(body, "系统SMTP正文") {
|
||||
t.Fatalf("system SMTP fallback body mismatch: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendEmail_IncompleteConfig 配置不完整应报错。
|
||||
func TestSendEmail_IncompleteConfig(t *testing.T) {
|
||||
n := New("cid", nil, nil)
|
||||
cases := []map[string]any{
|
||||
{"smtp_user": "u", "to_email": "t@e.com"}, // 缺 server
|
||||
{"smtp_server": "s", "to_email": "t@e.com"}, // 缺 user
|
||||
{"smtp_server": "s", "smtp_user": "u"}, // 缺 to
|
||||
{"smtp_user": "u", "to_email": "t@e.com"}, // 缺 server
|
||||
{"smtp_server": "s", "to_email": "t@e.com"}, // 缺 user
|
||||
{"smtp_server": "s", "smtp_user": "u"}, // 缺 to
|
||||
}
|
||||
for _, cfg := range cases {
|
||||
if err := n.sendEmail(cfg, "x"); err == nil {
|
||||
|
||||
@@ -140,6 +140,123 @@ func TestNotifyDelivery_WithChannel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyEvent_FiltersByChannelEventTypes(t *testing.T) {
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
hits := map[string]int{}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits[r.URL.Path]++
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
resOffline, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('掉线','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`/offline"}`, `["`+EventAccountOffline+`"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert offline channel: %v", err)
|
||||
}
|
||||
offlineID, _ := resOffline.LastInsertId()
|
||||
resDisabled, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('禁用','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`/disabled"}`, `["`+EventAccountDisabled+`"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert disabled channel: %v", err)
|
||||
}
|
||||
disabledID, _ := resDisabled.LastInsertId()
|
||||
for _, id := range []int64{offlineID, disabledID} {
|
||||
if _, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('cid',?,1)`, id); err != nil {
|
||||
t.Fatalf("insert binding: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyAccountEvent("cid", EventAccountOffline, "warn", "掉线", "正在恢复")
|
||||
if hits["/offline"] != 1 {
|
||||
t.Fatalf("offline channel hit=%d want 1", hits["/offline"])
|
||||
}
|
||||
if hits["/disabled"] != 0 {
|
||||
t.Fatalf("disabled channel should be filtered, hit=%d", hits["/disabled"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyAccountAlertClassifiesLegacyAlerts(t *testing.T) {
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
hits := map[string]int{}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits[r.URL.Path]++
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
resSecurity, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('风控','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`/security"}`, `["`+EventSecurityVerification+`"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert security channel: %v", err)
|
||||
}
|
||||
securityID, _ := resSecurity.LastInsertId()
|
||||
resToken, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('续期','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`/token"}`, `["`+EventTokenRenewal+`"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert token channel: %v", err)
|
||||
}
|
||||
tokenID, _ := resToken.LastInsertId()
|
||||
for _, id := range []int64{securityID, tokenID} {
|
||||
if _, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('cid',?,1)`, id); err != nil {
|
||||
t.Fatalf("insert binding: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyAccountAlert("cid", "warn", "闲鱼要求滑块验证", "请完成 captcha")
|
||||
if hits["/security"] != 1 {
|
||||
t.Fatalf("security channel hit=%d want 1", hits["/security"])
|
||||
}
|
||||
if hits["/token"] != 0 {
|
||||
t.Fatalf("token channel should not receive security alert, hit=%d", hits["/token"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyEventRejectsMalformedEventTypes(t *testing.T) {
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
hits := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits++
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
res, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('坏配置','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`"}`, `["`+EventAccountOffline+`"`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert malformed channel: %v", err)
|
||||
}
|
||||
channelID, _ := res.LastInsertId()
|
||||
if _, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('cid',?,1)`, channelID); err != nil {
|
||||
t.Fatalf("insert binding: %v", err)
|
||||
}
|
||||
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyAccountEvent("cid", EventAccountOffline, "warn", "掉线", "正在恢复")
|
||||
if hits != 0 {
|
||||
t.Fatalf("malformed event_types should deny delivery, hits=%d", hits)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseConfig 旧格式兼容。
|
||||
func TestParseConfig(t *testing.T) {
|
||||
// 标准 JSON。
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
@@ -126,6 +127,7 @@ func (s *Scheduler) runFixed(ctx context.Context, name, settingKey, intervalKey
|
||||
}
|
||||
|
||||
func (s *Scheduler) executeLoginRenew(ctx context.Context) {
|
||||
s.cleanupExpiredLogs(ctx)
|
||||
batchID := newBatchID()
|
||||
accounts, err := s.store.Cookies.ActiveRenewalAccounts(ctx)
|
||||
if err != nil {
|
||||
@@ -145,28 +147,29 @@ func (s *Scheduler) executeLoginRenew(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
|
||||
started := time.Now()
|
||||
runCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
res, err := s.mtop.CheckLoginStatusContext(runCtx, account.Value)
|
||||
if err != nil {
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", err.Error(), nil)
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", err.Error(), nil, time.Since(started))
|
||||
s.logger.Warn("login_renew 失败", "account", account.ID, "err", err)
|
||||
return
|
||||
}
|
||||
if res == nil {
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", "loginuser.get 未返回结果", nil)
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", "loginuser.get 未返回结果", nil, time.Since(started))
|
||||
return
|
||||
}
|
||||
updated := cookierefresh.ChangedCookieNames(account.Value, res.UpdatedCookies)
|
||||
if res.UpdatedCookies != "" && res.UpdatedCookies != account.Value {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
|
||||
if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated)
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated, time.Since(started))
|
||||
return
|
||||
}
|
||||
s.clearToken(ctx, account.ID)
|
||||
}
|
||||
s.addLoginLog(ctx, batchID, account.ID, res.Status, res.Message, updated)
|
||||
s.addLoginLog(ctx, batchID, account.ID, res.Status, res.Message, updated, time.Since(started))
|
||||
if res.Status == mtop.LoginStatusSessionExpired || res.Status == mtop.LoginStatusTokenEmpty {
|
||||
s.markSessionExpired(account.ID)
|
||||
s.triggerPasswordLoginAsync(account.ID)
|
||||
@@ -174,6 +177,7 @@ func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account d
|
||||
}
|
||||
|
||||
func (s *Scheduler) executeAPICookieRenew(ctx context.Context) {
|
||||
s.cleanupExpiredLogs(ctx)
|
||||
batchID := newBatchID()
|
||||
accounts, err := s.store.Cookies.ActiveRenewalAccounts(ctx)
|
||||
if err != nil {
|
||||
@@ -189,21 +193,24 @@ func (s *Scheduler) executeAPICookieRenew(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
|
||||
started := time.Now()
|
||||
stepDetails := []string{"api: hasLogin -> silentHasLogin -> setLoginSettings"}
|
||||
res, err := s.renewAPI(ctx, account.Value)
|
||||
if err != nil {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error()})
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), StepDetails: strings.Join(stepDetails, " | "), RenewMethod: "api", DurationMS: time.Since(started).Milliseconds(), RequestCount: 3})
|
||||
s.logger.Warn("api_cookie_renew 失败", "account", account.ID, "err", err)
|
||||
return
|
||||
}
|
||||
if res == nil {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "接口续期未返回结果"})
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "接口续期未返回结果", StepDetails: strings.Join(stepDetails, " | "), RenewMethod: "api", DurationMS: time.Since(started).Milliseconds(), RequestCount: 3})
|
||||
return
|
||||
}
|
||||
stepDetails = append(stepDetails, fmt.Sprintf("api_result: success=%v method=%s message=%s", res.Success, res.RenewMethod, res.Message))
|
||||
if res.Success {
|
||||
updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies)
|
||||
if res.NewCookies != "" && res.NewCookies != account.Value {
|
||||
if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)) {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated})
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: 3})
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -211,14 +218,14 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
if len(updated) > 0 {
|
||||
status = "cookie_updated"
|
||||
}
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: status, Message: res.Message, UpdatedCookieNames: updated, ResponseContent: res.ResponseText})
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: status, Message: res.Message, UpdatedCookieNames: updated, ResponseContent: res.ResponseText, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: 3})
|
||||
return
|
||||
}
|
||||
|
||||
if res.NewCookies != "" && res.NewCookies != account.Value {
|
||||
updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies)
|
||||
if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)) {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存部分 Cookie 失败", UpdatedCookieNames: updated})
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存部分 Cookie 失败", UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: 3})
|
||||
return
|
||||
}
|
||||
s.logger.Info("api_cookie_renew 保留接口返回的部分 Cookie 更新", "account", account.ID, "updated", strings.Join(updated, ","))
|
||||
@@ -228,24 +235,26 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
var browserCookies string
|
||||
var browserErr error
|
||||
if s.browser != nil {
|
||||
stepDetails = append(stepDetails, "browser: quick_enter")
|
||||
bctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
browserCookies, browserErr = s.browser.BrowserQuickRenew(bctx, account.ID, browserInput, !account.ShowBrowser)
|
||||
browserCookies, browserErr = s.browser.BrowserQuickRenew(bctx, account.ID, browserInput, browser.ResolveHeadless(account.ShowBrowser))
|
||||
cancel()
|
||||
} else {
|
||||
browserErr = fmt.Errorf("浏览器自动化未启用")
|
||||
}
|
||||
if browserErr == nil && browserCookies != "" {
|
||||
stepDetails = append(stepDetails, "api_verify: setLoginSettings after browser")
|
||||
verify, verifyErr := s.renewAPI(ctx, browserCookies)
|
||||
if verifyErr == nil && verify != nil && verify.Success {
|
||||
finalCookies := firstNonEmpty(verify.NewCookies, browserCookies)
|
||||
updated := cookierefresh.ChangedCookieNames(account.Value, finalCookies)
|
||||
if finalCookies != account.Value {
|
||||
if !s.saveRenewedCookies(ctx, account.ID, finalCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)) {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated})
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: "browser+api", DurationMS: time.Since(started).Milliseconds(), RequestCount: 6})
|
||||
return
|
||||
}
|
||||
}
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "browser_renewed", Message: "接口续期失败,浏览器续期成功,setLoginSettings验证通过", UpdatedCookieNames: updated, ResponseContent: verify.ResponseText})
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "browser_renewed", Message: "接口续期失败,浏览器续期成功,setLoginSettings验证通过", UpdatedCookieNames: updated, ResponseContent: verify.ResponseText, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: "browser+api", DurationMS: time.Since(started).Milliseconds(), RequestCount: 6})
|
||||
return
|
||||
}
|
||||
updated := cookierefresh.ChangedCookieNames(account.Value, browserCookies)
|
||||
@@ -269,10 +278,15 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
ErrorMessage: msg,
|
||||
UpdatedCookieNames: updated,
|
||||
ResponseContent: res.ResponseText,
|
||||
StepDetails: strings.Join(stepDetails, " | "),
|
||||
RenewMethod: "api+browser+password_required",
|
||||
DurationMS: time.Since(started).Milliseconds(),
|
||||
RequestCount: 6,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Scheduler) executeBrowserCookieRefresh(ctx context.Context) {
|
||||
s.cleanupExpiredLogs(ctx)
|
||||
batchID := newBatchID()
|
||||
accounts, err := s.store.Cookies.AllRenewalAccounts(ctx)
|
||||
if err != nil {
|
||||
@@ -313,31 +327,32 @@ func (s *Scheduler) executeBrowserCookieRefresh(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, account db.RenewalAccount, schedule db.CookieRefreshSchedule) {
|
||||
started := time.Now()
|
||||
if s.browser == nil {
|
||||
schedule.LastStatus = "failed"
|
||||
schedule.LastErrorMessage = "浏览器自动化未启用"
|
||||
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: schedule.LastErrorMessage})
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: schedule.LastErrorMessage, RenewMethod: "browser", StepDetails: "browser disabled", DurationMS: time.Since(started).Milliseconds()})
|
||||
return
|
||||
}
|
||||
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
oldSnapshot := cookierefresh.SnapshotFromMetadata(account.MetadataJSON)
|
||||
newCookies, newSnapshot, err := s.browser.CookiesRefreshSnapshot(runCtx, account.ID, account.Value, oldSnapshot, !account.ShowBrowser)
|
||||
newCookies, newSnapshot, err := s.browser.CookiesRefreshSnapshot(runCtx, account.ID, account.Value, oldSnapshot, browser.ResolveHeadless(account.ShowBrowser))
|
||||
if err != nil {
|
||||
schedule.ConsecutiveFailures++
|
||||
schedule.LastStatus = "failed"
|
||||
schedule.LastError = err.Error()
|
||||
schedule.LastErrorMessage = err.Error()
|
||||
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), NextExpireAt: schedule.ExpireAt})
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), NextExpireAt: schedule.ExpireAt, RenewMethod: "browser", StepDetails: fmt.Sprintf("snapshot=%v reload=3", len(oldSnapshot) > 0), DurationMS: time.Since(started).Milliseconds(), RequestCount: 4})
|
||||
s.logger.Warn("cookies_refresh 失败", "account", account.ID, "err", err)
|
||||
return
|
||||
}
|
||||
metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, newSnapshot)
|
||||
updated := cookierefresh.ChangedSnapshotLabels(oldSnapshot, newSnapshot)
|
||||
if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, newCookies, metadata, time.Now().Unix()); err != nil {
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败: " + err.Error(), UpdatedCookieNames: updated})
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败: " + err.Error(), UpdatedCookieNames: updated, RenewMethod: "browser", StepDetails: fmt.Sprintf("snapshot=%v reload=3", len(oldSnapshot) > 0), DurationMS: time.Since(started).Milliseconds(), RequestCount: 4})
|
||||
return
|
||||
}
|
||||
s.clearToken(ctx, account.ID)
|
||||
@@ -366,6 +381,10 @@ func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string,
|
||||
Message: fmt.Sprintf("页面校验通过,全量获取到 %d 个浏览器Cookie", len(newSnapshot)),
|
||||
UpdatedCookieNames: updated,
|
||||
NextExpireAt: nextExpire,
|
||||
RenewMethod: "browser",
|
||||
StepDetails: fmt.Sprintf("snapshot=%v reload=3 modal_check=true", len(oldSnapshot) > 0),
|
||||
DurationMS: time.Since(started).Milliseconds(),
|
||||
RequestCount: 4,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -384,14 +403,34 @@ func (s *Scheduler) saveRenewedCookies(ctx context.Context, cookieID, cookieStr,
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Scheduler) addLoginLog(ctx context.Context, batchID, cookieID, status, message string, updated []string) {
|
||||
_ = s.store.Renewal.AddLoginRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: cookieID, Status: status, Message: message, UpdatedCookieNames: updated})
|
||||
func (s *Scheduler) addLoginLog(ctx context.Context, batchID, cookieID, status, message string, updated []string, duration time.Duration) {
|
||||
_ = s.store.Renewal.AddLoginRenewLog(ctx, db.RenewalLog{
|
||||
BatchID: batchID,
|
||||
CookieID: cookieID,
|
||||
Status: status,
|
||||
Message: message,
|
||||
UpdatedCookieNames: updated,
|
||||
RenewMethod: "loginuser.get",
|
||||
StepDetails: fmt.Sprintf("loginuser.get status=%s message=%s updated=%d", status, message, len(updated)),
|
||||
DurationMS: duration.Milliseconds(),
|
||||
RequestCount: 1,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Scheduler) addAPILog(ctx context.Context, log db.RenewalLog) {
|
||||
_ = s.store.Renewal.AddAPICookieRenewLog(ctx, log)
|
||||
}
|
||||
|
||||
func (s *Scheduler) cleanupExpiredLogs(ctx context.Context) {
|
||||
if s.store == nil || s.store.Renewal == nil {
|
||||
return
|
||||
}
|
||||
days := s.settingInt(ctx, "renewal_log_retention_days", 10)
|
||||
if err := s.store.Renewal.CleanupLogs(ctx, days); err != nil {
|
||||
s.logger.Warn("清理续期日志失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) markSessionExpired(cookieID string) {
|
||||
s.cooldown.MarkSessionExpired(cookieID)
|
||||
}
|
||||
@@ -457,6 +496,21 @@ func (s *Scheduler) settingInterval(ctx context.Context, key string, defaultInte
|
||||
return defaultInterval
|
||||
}
|
||||
|
||||
func (s *Scheduler) settingInt(ctx context.Context, key string, defaultValue int) int {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return defaultValue
|
||||
}
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
if err != nil || strings.TrimSpace(value) == "" {
|
||||
return defaultValue
|
||||
}
|
||||
n, err := strconv.Atoi(strings.TrimSpace(value))
|
||||
if err != nil || n < 0 {
|
||||
return defaultValue
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (s *Scheduler) clearToken(ctx context.Context, cookieID string) {
|
||||
if s.store.Tokens == nil {
|
||||
return
|
||||
|
||||
@@ -76,6 +76,10 @@ type apiRenewLogSnapshot struct {
|
||||
errorMessage string
|
||||
updatedCookieNames string
|
||||
responseContent string
|
||||
stepDetails string
|
||||
renewMethod string
|
||||
durationMS int64
|
||||
requestCount int
|
||||
}
|
||||
|
||||
func createSchedulerAccount(t *testing.T, store *db.Store, cookieID, cookieValue string) db.RenewalAccount {
|
||||
@@ -99,11 +103,14 @@ func lastAPIRenewLog(t *testing.T, store *db.Store, cookieID string) apiRenewLog
|
||||
t.Helper()
|
||||
var log apiRenewLogSnapshot
|
||||
err := store.DB.QueryRowContext(context.Background(),
|
||||
`SELECT status, COALESCE(message,''), COALESCE(error_message,''), COALESCE(updated_cookie_names,''), COALESCE(response_content,'')
|
||||
`SELECT status, COALESCE(message,''), COALESCE(error_message,''), COALESCE(updated_cookie_names,''),
|
||||
COALESCE(response_content,''), COALESCE(step_details,''), COALESCE(renew_method,''),
|
||||
COALESCE(duration_ms,0), COALESCE(request_count,0)
|
||||
FROM scheduled_api_cookie_renew_log
|
||||
WHERE cookie_id=?
|
||||
ORDER BY id DESC LIMIT 1`, cookieID).
|
||||
Scan(&log.status, &log.message, &log.errorMessage, &log.updatedCookieNames, &log.responseContent)
|
||||
Scan(&log.status, &log.message, &log.errorMessage, &log.updatedCookieNames, &log.responseContent,
|
||||
&log.stepDetails, &log.renewMethod, &log.durationMS, &log.requestCount)
|
||||
if err != nil {
|
||||
t.Fatalf("query api renew log: %v", err)
|
||||
}
|
||||
@@ -230,6 +237,73 @@ func TestSchedulerSettingIntervalOverrides(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulerSettingIntOverrides(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
|
||||
if got := s.settingInt(ctx, "missing_int", 10); got != 10 {
|
||||
t.Fatalf("missing setting=%d want 10", got)
|
||||
}
|
||||
if err := store.Settings.Set(ctx, "renewal_log_retention_days", "20"); err != nil {
|
||||
t.Fatalf("Set int: %v", err)
|
||||
}
|
||||
if got := s.settingInt(ctx, "renewal_log_retention_days", 10); got != 20 {
|
||||
t.Fatalf("setting int=%d want 20", got)
|
||||
}
|
||||
if err := store.Settings.Set(ctx, "renewal_log_retention_days", "-1"); err != nil {
|
||||
t.Fatalf("Set invalid: %v", err)
|
||||
}
|
||||
if got := s.settingInt(ctx, "renewal_log_retention_days", 10); got != 10 {
|
||||
t.Fatalf("invalid setting int=%d want 10", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewalCleanupLogsUsesRetentionDays(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
cookie := createSchedulerAccount(t, store, "cid-cleanup", "unb=1")
|
||||
_ = cookie
|
||||
|
||||
for _, table := range []string{
|
||||
"scheduled_cookies_refresh_log",
|
||||
"scheduled_login_renew_log",
|
||||
"scheduled_api_cookie_renew_log",
|
||||
} {
|
||||
if _, err := store.DB.ExecContext(ctx,
|
||||
`INSERT INTO `+table+` (batch_id, cookie_id, status, created_at) VALUES ('old', 'cid-cleanup', 'failed', datetime('now','-20 days'))`); err != nil {
|
||||
t.Fatalf("insert old %s: %v", table, err)
|
||||
}
|
||||
if _, err := store.DB.ExecContext(ctx,
|
||||
`INSERT INTO `+table+` (batch_id, cookie_id, status, created_at) VALUES ('new', 'cid-cleanup', 'success', CURRENT_TIMESTAMP)`); err != nil {
|
||||
t.Fatalf("insert new %s: %v", table, err)
|
||||
}
|
||||
}
|
||||
if err := store.Settings.Set(ctx, "renewal_log_retention_days", "10"); err != nil {
|
||||
t.Fatalf("set retention: %v", err)
|
||||
}
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
s.cleanupExpiredLogs(ctx)
|
||||
for _, table := range []string{
|
||||
"scheduled_cookies_refresh_log",
|
||||
"scheduled_login_renew_log",
|
||||
"scheduled_api_cookie_renew_log",
|
||||
} {
|
||||
var oldRows, newRows int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM `+table+` WHERE batch_id='old'`).Scan(&oldRows); err != nil {
|
||||
t.Fatalf("count old %s: %v", table, err)
|
||||
}
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM `+table+` WHERE batch_id='new'`).Scan(&newRows); err != nil {
|
||||
t.Fatalf("count new %s: %v", table, err)
|
||||
}
|
||||
if oldRows != 0 || newRows != 1 {
|
||||
t.Fatalf("%s cleanup old=%d new=%d, want old=0 new=1", table, oldRows, newRows)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICookieRenewOneSavesPartialCookiesBeforePasswordLogin(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
@@ -380,4 +454,13 @@ func TestAPICookieRenewOneBrowserRenewedAfterVerifySuccess(t *testing.T) {
|
||||
if !strings.Contains(log.responseContent, "silent-browser-ok") {
|
||||
t.Fatalf("response_content 应记录验证阶段 silentHasLogin 响应: %+v", log)
|
||||
}
|
||||
if log.renewMethod != "browser+api" || log.requestCount != 6 {
|
||||
t.Fatalf("浏览器兜底日志应记录方法和请求数: %+v", log)
|
||||
}
|
||||
if !strings.Contains(log.stepDetails, "browser: quick_enter") || !strings.Contains(log.stepDetails, "api_verify") {
|
||||
t.Fatalf("step_details 未记录浏览器兜底步骤: %+v", log)
|
||||
}
|
||||
if log.durationMS < 0 {
|
||||
t.Fatalf("duration_ms 不应为负数: %+v", log)
|
||||
}
|
||||
}
|
||||
@@ -249,6 +249,7 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
|
||||
Password string `json:"password"`
|
||||
LoginPassword string `json:"login_password"`
|
||||
ShowBrowser bool `json:"show_browser"`
|
||||
ClearPassword bool `json:"clear_password"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
@@ -258,7 +259,9 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
|
||||
if password == "" {
|
||||
password = req.LoginPassword
|
||||
}
|
||||
if password == "" && detail != nil {
|
||||
if req.ClearPassword {
|
||||
password = ""
|
||||
} else if password == "" && detail != nil {
|
||||
password = detail.Password
|
||||
}
|
||||
if err := s.Store.Cookies.UpdateLoginInfo(r.Context(), cid, req.Username, password, req.ShowBrowser); err != nil {
|
||||
|
||||
@@ -255,6 +255,22 @@ func TestUpdateCookieLoginInfo(t *testing.T) {
|
||||
if d.Username != "u2" || d.Password != "p1" || d.ShowBrowser {
|
||||
t.Fatalf("空密码更新应保留原密码并更新其他字段: %+v", d)
|
||||
}
|
||||
|
||||
body = `{"username":"u2","clear_password":true,"show_browser":false}`
|
||||
req = httptest.NewRequest(http.MethodPut, "/cookies/acc1/login-info", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("clear password status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
d, err = store.Cookies.GetDetails(ctx, "acc1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetDetails after clear password: %v", err)
|
||||
}
|
||||
if d.Username != "u2" || d.Password != "" || d.ShowBrowser {
|
||||
t.Fatalf("clear_password 应清空密码并保留其他更新: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCookieLoginInfoBadJSON 非法 JSON 400。
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -70,8 +71,7 @@ func TestSetDefaultReplyBadJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetDefaultReplyNotFound 不存在返回默认。
|
||||
func TestGetDefaultReplyNotFound(t *testing.T) {
|
||||
func TestGetDefaultReplyMissingAccountIsNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
@@ -81,8 +81,23 @@ func TestGetDefaultReplyNotFound(t *testing.T) {
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在账号应 404,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/default-replies/acc1", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
@@ -91,6 +106,32 @@ func TestGetDefaultReplyNotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDefaultReplyRejectsCrossUserAccount(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Users.Create(ctx, "default-other", "default-other@example.com", "pw"); err != nil {
|
||||
t.Fatalf("create other user: %v", err)
|
||||
}
|
||||
other, err := store.Users.GetByUsername(ctx, "default-other")
|
||||
if err != nil {
|
||||
t.Fatalf("get other user: %v", err)
|
||||
}
|
||||
if err := store.Cookies.Save(ctx, "other-acc", "unb=456; _m_h5_tk=tk2_1;", other.ID); err != nil {
|
||||
t.Fatalf("save other cookie: %v", err)
|
||||
}
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/default-replies/other-acc", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("跨用户账号应 403,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteDefaultReply 删除。
|
||||
func TestDeleteDefaultReply(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -41,18 +40,7 @@ func (s *Server) mountDefaultRepliesReal(r chi.Router) {
|
||||
|
||||
func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return
|
||||
}
|
||||
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
|
||||
if d.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
dr, err := s.Store.DefaultReps.Get(r.Context(), cid)
|
||||
|
||||
@@ -443,24 +443,64 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
var req struct {
|
||||
ItemTitle string `json:"item_title"`
|
||||
ItemDescription string `json:"item_description"`
|
||||
ItemCategory string `json:"item_category"`
|
||||
ItemPrice string `json:"item_price"`
|
||||
ItemDetail string `json:"item_detail"`
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
|
||||
IsMultiQtyShip bool `json:"is_multi_qty_ship"`
|
||||
ItemTitle *string `json:"item_title"`
|
||||
ItemDescription *string `json:"item_description"`
|
||||
ItemCategory *string `json:"item_category"`
|
||||
ItemPrice *string `json:"item_price"`
|
||||
ItemDetail *string `json:"item_detail"`
|
||||
IsMultiSpec *bool `json:"is_multi_spec"`
|
||||
MultiQuantityDelivery *bool `json:"multi_quantity_delivery"`
|
||||
IsMultiQtyShip *bool `json:"is_multi_qty_ship"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{
|
||||
CookieID: cid, ItemID: itemID, ItemTitle: req.ItemTitle, ItemDescription: req.ItemDescription,
|
||||
ItemCategory: req.ItemCategory, ItemPrice: req.ItemPrice, ItemDetail: req.ItemDetail,
|
||||
IsMultiSpec: req.IsMultiSpec, MultiQuantityDelivery: req.MultiQuantityDelivery || req.IsMultiQtyShip,
|
||||
}); err != nil {
|
||||
existing, err := s.Store.Items.Get(r.Context(), cid, itemID)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "商品不存在")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
row := &db.ItemInfoRow{
|
||||
CookieID: cid,
|
||||
ItemID: itemID,
|
||||
ItemTitle: existing.ItemTitle,
|
||||
ItemDescription: existing.ItemDescription,
|
||||
ItemCategory: existing.ItemCategory,
|
||||
ItemPrice: existing.ItemPrice,
|
||||
ItemDetail: existing.ItemDetail,
|
||||
IsMultiSpec: existing.IsMultiSpec,
|
||||
MultiQuantityDelivery: existing.MultiQuantityDelivery,
|
||||
}
|
||||
if req.ItemTitle != nil {
|
||||
row.ItemTitle = *req.ItemTitle
|
||||
}
|
||||
if req.ItemDescription != nil {
|
||||
row.ItemDescription = *req.ItemDescription
|
||||
}
|
||||
if req.ItemCategory != nil {
|
||||
row.ItemCategory = *req.ItemCategory
|
||||
}
|
||||
if req.ItemPrice != nil {
|
||||
row.ItemPrice = *req.ItemPrice
|
||||
}
|
||||
if req.ItemDetail != nil {
|
||||
row.ItemDetail = *req.ItemDetail
|
||||
}
|
||||
if req.IsMultiSpec != nil {
|
||||
row.IsMultiSpec = *req.IsMultiSpec
|
||||
}
|
||||
if req.MultiQuantityDelivery != nil {
|
||||
row.MultiQuantityDelivery = *req.MultiQuantityDelivery
|
||||
}
|
||||
if req.IsMultiQtyShip != nil {
|
||||
row.MultiQuantityDelivery = *req.IsMultiQtyShip
|
||||
}
|
||||
if err := s.Store.Items.Upsert(r.Context(), row); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -429,7 +429,11 @@ func TestItemCRUD(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-crud','商品C')`)
|
||||
if _, err := store.DB.ExecContext(ctx, `INSERT INTO item_info
|
||||
(cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery)
|
||||
VALUES ('acc1','it-crud','商品C','原描述','原分类','12.00','原详情',1,1)`); err != nil {
|
||||
t.Fatalf("seed item: %v", err)
|
||||
}
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
@@ -465,6 +469,61 @@ func TestItemCRUD(t *testing.T) {
|
||||
if rec3.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec3.Code, rec3.Body.String())
|
||||
}
|
||||
updated, err := store.Items.Get(ctx, "acc1", "it-crud")
|
||||
if err != nil {
|
||||
t.Fatalf("get updated item: %v", err)
|
||||
}
|
||||
if updated.ItemTitle != "改名商品" || updated.ItemPrice != "88.00" {
|
||||
t.Fatalf("update text fields failed: %+v", updated)
|
||||
}
|
||||
if updated.ItemDescription != "原描述" || updated.ItemCategory != "原分类" || updated.ItemDetail != "原详情" {
|
||||
t.Fatalf("omitted text fields should be preserved: %+v", updated)
|
||||
}
|
||||
if !updated.IsMultiSpec || !updated.MultiQuantityDelivery {
|
||||
t.Fatalf("omitted multi flags should be preserved: %+v", updated)
|
||||
}
|
||||
|
||||
// 显式传空字符串时允许清空文本字段。
|
||||
clearBody := `{"item_description":""}`
|
||||
reqClear := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud", strings.NewReader(clearBody))
|
||||
reqClear.AddCookie(cookie)
|
||||
recClear := httptest.NewRecorder()
|
||||
h.ServeHTTP(recClear, reqClear)
|
||||
if recClear.Code != 200 {
|
||||
t.Fatalf("clear text status=%d body=%s", recClear.Code, recClear.Body.String())
|
||||
}
|
||||
updated, err = store.Items.Get(ctx, "acc1", "it-crud")
|
||||
if err != nil {
|
||||
t.Fatalf("get cleared item: %v", err)
|
||||
}
|
||||
if updated.ItemDescription != "" || updated.ItemCategory != "原分类" || updated.ItemDetail != "原详情" {
|
||||
t.Fatalf("explicit empty text should clear only requested field: %+v", updated)
|
||||
}
|
||||
|
||||
// 显式传 false 时仍允许清除布尔配置。
|
||||
updFlagsBody := `{"item_title":"改名商品","item_price":"88.00","is_multi_spec":false,"is_multi_qty_ship":false}`
|
||||
reqFlags := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud", strings.NewReader(updFlagsBody))
|
||||
reqFlags.AddCookie(cookie)
|
||||
recFlags := httptest.NewRecorder()
|
||||
h.ServeHTTP(recFlags, reqFlags)
|
||||
if recFlags.Code != 200 {
|
||||
t.Fatalf("update flags status=%d body=%s", recFlags.Code, recFlags.Body.String())
|
||||
}
|
||||
updated, err = store.Items.Get(ctx, "acc1", "it-crud")
|
||||
if err != nil {
|
||||
t.Fatalf("get updated flags item: %v", err)
|
||||
}
|
||||
if updated.IsMultiSpec || updated.MultiQuantityDelivery {
|
||||
t.Fatalf("explicit false flags should be persisted: %+v", updated)
|
||||
}
|
||||
|
||||
reqMissing := httptest.NewRequest(http.MethodPut, "/items/acc1/missing-item", strings.NewReader(`{"item_title":"不会创建"}`))
|
||||
reqMissing.AddCookie(cookie)
|
||||
recMissing := httptest.NewRecorder()
|
||||
h.ServeHTTP(recMissing, reqMissing)
|
||||
if recMissing.Code != http.StatusNotFound {
|
||||
t.Fatalf("missing item update should be 404, got %d body=%s", recMissing.Code, recMissing.Body.String())
|
||||
}
|
||||
|
||||
// 多规格 + 多件发货。
|
||||
multiBody := `{"multi_quantity_delivery":true}`
|
||||
|
||||
@@ -78,13 +78,13 @@ func TestCreateChannelBadJSON(t *testing.T) {
|
||||
|
||||
// TestUpdateChannel 更新渠道。
|
||||
func TestUpdateChannel(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 创建。
|
||||
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
|
||||
body := `{"name":"钉钉","type":"dingtalk","config":"{\"webhook_url\":\"https://example.com\"}","event_types":"[\"account_offline\"]","enabled":true}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
@@ -93,8 +93,8 @@ func TestUpdateChannel(t *testing.T) {
|
||||
json.Unmarshal(rec.Body.Bytes(), &cr)
|
||||
id := int64(cr["id"].(float64))
|
||||
|
||||
// 更新。
|
||||
upd := `{"name":"改名钉钉","type":"dingtalk","config":"{}","enabled":false}`
|
||||
// 部分更新:只切换 enabled,不应清空 name/type/config/event_types。
|
||||
upd := `{"enabled":false}`
|
||||
req2 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(upd))
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
@@ -102,6 +102,33 @@ func TestUpdateChannel(t *testing.T) {
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec2.Code, rec2.Body.String())
|
||||
}
|
||||
row, err := store.Notifications.GetChannelRowForUser(context.Background(), id, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("get channel row: %v", err)
|
||||
}
|
||||
if row == nil {
|
||||
t.Fatal("channel row missing")
|
||||
}
|
||||
if row.Name != "钉钉" || row.Type != "dingtalk" || row.Config != `{"webhook_url":"https://example.com"}` ||
|
||||
row.EventTypes != `["account_offline"]` || row.Enabled {
|
||||
t.Fatalf("partial update should preserve omitted fields and change enabled: %+v", row)
|
||||
}
|
||||
|
||||
// 显式传空 event_types 表示恢复为接收全部事件,其它字段仍保留。
|
||||
req3 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(`{"event_types":""}`))
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != 200 {
|
||||
t.Fatalf("clear event_types status=%d body=%s", rec3.Code, rec3.Body.String())
|
||||
}
|
||||
row, err = store.Notifications.GetChannelRowForUser(context.Background(), id, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("get channel row after clear: %v", err)
|
||||
}
|
||||
if row.EventTypes != "" || row.Name != "钉钉" || row.Config != `{"webhook_url":"https://example.com"}` {
|
||||
t.Fatalf("event_types clear should not affect other fields: %+v", row)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateChannelBadID 无效 ID 400。
|
||||
@@ -294,6 +321,29 @@ func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
|
||||
if len(ids) != 1 || int64(ids[0].(float64)) != ownID {
|
||||
t.Fatalf("bindings should filter dirty binding: %+v", got)
|
||||
}
|
||||
|
||||
updateOtherReq := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(otherID), strings.NewReader(`{"enabled":false}`))
|
||||
updateOtherReq.AddCookie(cookie)
|
||||
updateOtherRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(updateOtherRec, updateOtherReq)
|
||||
if updateOtherRec.Code != http.StatusForbidden {
|
||||
t.Fatalf("cross-user update should be 403, got %d body=%s", updateOtherRec.Code, updateOtherRec.Body.String())
|
||||
}
|
||||
otherRow, err := store.Notifications.GetChannelRowForUser(ctx, otherID, u2.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("get other channel: %v", err)
|
||||
}
|
||||
if otherRow == nil || !otherRow.Enabled {
|
||||
t.Fatalf("cross-user update should not mutate other channel: %+v", otherRow)
|
||||
}
|
||||
|
||||
deleteOtherReq := httptest.NewRequest(http.MethodDelete, "/notification-channels/"+itoa(otherID), nil)
|
||||
deleteOtherReq.AddCookie(cookie)
|
||||
deleteOtherRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(deleteOtherRec, deleteOtherReq)
|
||||
if deleteOtherRec.Code != http.StatusForbidden {
|
||||
t.Fatalf("cross-user delete should be 403, got %d body=%s", deleteOtherRec.Code, deleteOtherRec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteMessageNotification 删除单条消息通知。
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -37,17 +38,18 @@ func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
|
||||
sess := authSess(r)
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
EventTypes string `json:"event_types"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil || req.Name == "" || req.Type == "" {
|
||||
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
|
||||
return
|
||||
}
|
||||
id, err := s.Store.Notifications.CreateChannel(r.Context(), &db.NotificationChannelRow{
|
||||
Name: req.Name, Type: req.Type, Config: req.Config, Enabled: req.Enabled, UserID: sess.UserID,
|
||||
Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled, UserID: sess.UserID,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "创建失败")
|
||||
@@ -63,21 +65,50 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Name *string `json:"name"`
|
||||
Type *string `json:"type"`
|
||||
Config *string `json:"config"`
|
||||
EventTypes *string `json:"event_types"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
sess := authSess(r)
|
||||
row, err := s.Store.Notifications.GetChannelRowForUser(r.Context(), id, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
if err := s.Store.Notifications.UpdateChannel(r.Context(), &db.NotificationChannelRow{
|
||||
ID: id, Name: req.Name, Type: req.Type, Config: req.Config, Enabled: req.Enabled,
|
||||
}); err != nil {
|
||||
if row == nil {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
if req.Name != nil {
|
||||
row.Name = *req.Name
|
||||
}
|
||||
if req.Type != nil {
|
||||
row.Type = *req.Type
|
||||
}
|
||||
if req.Config != nil {
|
||||
row.Config = *req.Config
|
||||
}
|
||||
if req.EventTypes != nil {
|
||||
row.EventTypes = *req.EventTypes
|
||||
}
|
||||
if req.Enabled != nil {
|
||||
row.Enabled = *req.Enabled
|
||||
}
|
||||
if row.Name == "" || row.Type == "" {
|
||||
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
|
||||
return
|
||||
}
|
||||
if err := s.Store.Notifications.UpdateChannelForUser(r.Context(), row, sess.UserID); err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
@@ -90,10 +121,12 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
return
|
||||
}
|
||||
if err := s.Store.Notifications.DeleteChannel(r.Context(), id); err != nil {
|
||||
sess := authSess(r)
|
||||
if err := s.Store.Notifications.DeleteChannelForUser(r.Context(), id, sess.UserID); err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ func (s *Server) runPasswordLoginSession(ctx context.Context, session *passwordL
|
||||
cookies map[string]string
|
||||
err error
|
||||
)
|
||||
headless := !session.ShowBrowser
|
||||
headless := browser.ResolveHeadless(session.ShowBrowser)
|
||||
if runner, ok := s.PasswordLogin.(passwordLoginEventRunner); ok {
|
||||
cookies, err = runner.PasswordLoginWithEvents(ctx, session.Account, password, session.AccountID, "", headless, func(event browser.PasswordLoginEvent) {
|
||||
s.applyPasswordLoginEvent(session, event)
|
||||
@@ -405,10 +405,6 @@ func cookieAccountID(cookies map[string]string, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func loginStatusForPasswordError(err error) string {
|
||||
return browser.PasswordLoginEventFromError(err).Status
|
||||
}
|
||||
|
||||
func passwordLoginReason(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
|
||||
@@ -3,10 +3,13 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/logging"
|
||||
)
|
||||
|
||||
// TestListAIModels 通过 mock OpenAI 端点返回模型列表。
|
||||
@@ -103,6 +106,38 @@ func TestSetSettingBadJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) {
|
||||
defer logging.Level.Set(slog.LevelInfo)
|
||||
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
badReq := httptest.NewRequest(http.MethodPut, "/system-settings/log_level", strings.NewReader(`{"value":"verbose"}`))
|
||||
badReq.AddCookie(cookie)
|
||||
badRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(badRec, badReq)
|
||||
if badRec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid log level should be 400, got %d body=%s", badRec.Code, badRec.Body.String())
|
||||
}
|
||||
|
||||
goodReq := httptest.NewRequest(http.MethodPut, "/system-settings/log_level", strings.NewReader(`{"value":"debug"}`))
|
||||
goodReq.AddCookie(cookie)
|
||||
goodRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(goodRec, goodReq)
|
||||
if goodRec.Code != http.StatusOK {
|
||||
t.Fatalf("valid log level should be 200, got %d body=%s", goodRec.Code, goodRec.Body.String())
|
||||
}
|
||||
if got := logging.Level.Level(); got != slog.LevelDebug {
|
||||
t.Fatalf("runtime log level=%v want debug", got)
|
||||
}
|
||||
saved, err := srv.Store.Settings.Get(context.Background(), "log_level")
|
||||
if err != nil || saved != "debug" {
|
||||
t.Fatalf("saved log_level=%q err=%v", saved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemSettingsRequireAdmin(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
@@ -225,8 +260,7 @@ func TestSetAIReplyBadJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetAIReplyNotFound 不存在账号返回默认值。
|
||||
func TestGetAIReplyNotFound(t *testing.T) {
|
||||
func TestGetAIReplyMissingAccountIsNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
@@ -236,8 +270,23 @@ func TestGetAIReplyNotFound(t *testing.T) {
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在账号应 404,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAIReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/logging"
|
||||
)
|
||||
|
||||
const maxOpenAIModelsResponseBytes = 4 << 20
|
||||
@@ -60,6 +61,12 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if key == "log_level" {
|
||||
if err := logging.SetLevel(req.Value); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.Store.Settings.Set(r.Context(), key, req.Value); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
@@ -115,18 +122,7 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return
|
||||
}
|
||||
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
|
||||
if d.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
cfg, err := s.Store.AIReply.Get(r.Context(), cid)
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import{j as e,r as o,b as ue,c as ut,d as pt}from"./react-vendor-DZnRGM0-.js";import{L as ht,U as Js,S as Ys,C as us,B as Gs,Z as ps,a as qe,b as bs,c as Ks,d as gt,A as Ns,D as bt,e as vs,P as Xs,f as Ge,E as Zs,T as yt,g as _e,Q as is,h as hs,i as Fe,j as Te,k as ls,l as ws,R as ke,m as Hs,n as ft,o as Ae,X as xe,K as jt,p as Ye,q as Be,r as Le,s as De,t as _s,u as Nt,v as ze,w as vt,x as wt,y as Je,z as _t,F as ks,I as Cs,G as Ss,H as kt,J as Ct,M as os,N as Ze,O as et,V as St,W as $t,Y as gs,_ as It,$ as At,a0 as $s,a1 as Dt,a2 as st,a3 as as,a4 as tt,a5 as Lt,a6 as Pt,a7 as ys,a8 as at,a9 as Ft,aa as Rt}from"./icons-vendor-BmeuAUrP.js";import{R as He,B as Et,X as Is,Y as As,T as ds,a as Ot,C as cs,A as Mt,b as Tt,c as qt,P as Ds,d as Ls,L as Bt}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))h(u);new MutationObserver(u=>{for(const m of u)if(m.type==="childList")for(const w of m.addedNodes)w.tagName==="LINK"&&w.rel==="modulepreload"&&h(w)}).observe(document,{childList:!0,subtree:!0});function r(u){const m={};return u.integrity&&(m.integrity=u.integrity),u.referrerPolicy&&(m.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?m.credentials="include":u.crossOrigin==="anonymous"?m.credentials="omit":m.credentials="same-origin",m}function h(u){if(u.ep)return;u.ep=!0;const m=r(u);fetch(u.href,m)}})();const zt=({activeTab:s,onNavigate:a,onLogout:r})=>{const h=[{id:"dashboard",icon:ht,label:"仪表盘"},{id:"accounts",icon:Js,label:"账号管理"},{id:"orders",icon:Ys,label:"订单管理"},{id:"cards",icon:us,label:"卡密库存"},{id:"items",icon:Gs,label:"商品列表"},{id:"rules",icon:ps,label:"自动化规则"},{id:"notifications",icon:qe,label:"通知设置"},{id:"settings",icon:bs,label:"系统与AI"}];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:h.map(u=>{const m=u.icon,w=s===u.id;return e.jsxs("button",{onClick:()=>a(u.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${w?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(m,{className:`w-5 h-5 transition-colors ${w?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:u.label}),w&&e.jsx(Ks,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},u.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:r,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(gt,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Ut=s=>{if(!s)return"";const a=new URLSearchParams;for(const[h,u]of Object.entries(s))u!=null&&a.set(h,String(u));const r=a.toString();return r?`?${r}`:""},ns=async(s,a,r={})=>{const h=Ut(r.params),u=`${a}${h}`,m=await fetch(u,{method:s,credentials:"include",headers:{...r.body===void 0?{}:{"Content-Type":"application/json"}},body:r.body===void 0?void 0:JSON.stringify(r.body)}),I=(m.headers.get("content-type")||"").includes("application/json");if(!m.ok){const p=I?await m.json().catch(()=>{}):await m.text().catch(()=>{}),W=typeof p=="string"?p:(p==null?void 0:p.detail)||(p==null?void 0:p.message)||(p==null?void 0:p.msg);throw new Error(W||`请求失败: ${m.status}`)}return I?await m.json():await m.text()},ie=async(s,a)=>ns("GET",s,{params:a}),de=async(s,a)=>ns("POST",s,{body:a}),fe=async(s,a)=>ns("PUT",s,{body:a}),Ee=async(s,a)=>ns("DELETE",s,{params:a}),fs=async(s,a)=>{const r=await fetch(s,{method:"POST",credentials:"include",body:a}),m=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){const w=typeof m=="string"?m:(m==null?void 0:m.detail)||(m==null?void 0:m.message)||(m==null?void 0:m.msg),I=new Error(w||"请求失败: "+r.status);throw I.payload=m,Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(bs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>$(null),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:q,children:"取消"}),e.jsxs("button",{onClick:Ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:q,children:[q?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Le,{className:"w-4 h-4"}),q?"保存中...":"保存"]})]})})]})}),document.body)]})},Bs=({status:s})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600"},r={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[s]||a.cancelled}`,children:r[s]||s})},Xa=()=>{const[s,a]=o.useState([]),[r,h]=o.useState([]),[u,m]=o.useState([]),[w,I]=o.useState({}),[p,W]=o.useState("all"),[b,Y]=o.useState(""),[G,M]=o.useState(1),[E,X]=o.useState(1),[re,Z]=o.useState(!1),[R,te]=o.useState(!1),[T,F]=o.useState(!1),[L,Q]=o.useState(!1),[A,$]=o.useState(null),[d,z]=o.useState(null),[H,J]=o.useState({}),[U,C]=o.useState(!1),[k,c]=o.useState(""),[j,N]=o.useState(!1),[q,D]=o.useState(null),[ee,O]=o.useState(null),[i,P]=o.useState(null),[ae,ne]=o.useState(null),x=t=>{if(!b.trim())return t;const g=b.toLowerCase().trim();return t.filter(S=>{var l,v,le,$e,Se,ve;return((l=S.order_id)==null?void 0:l.toLowerCase().includes(g))||((v=S.item_id)==null?void 0:v.toLowerCase().includes(g))||((le=S.buyer_id)==null?void 0:le.toLowerCase().includes(g))||(($e=S.item_title)==null?void 0:$e.toLowerCase().includes(g))||((Se=S.receiver_name)==null?void 0:Se.toLowerCase().includes(g))||((ve=S.receiver_phone)==null?void 0:ve.toLowerCase().includes(g))})},y=async()=>{Z(!0);try{if(b.trim()){let t=[],g=1,S=!0;for(;S;){const l=await Fs(void 0,p,g,100);t=[...t,...l.data],S=g<l.total_pages,g++}h(t),a(x(t)),X(1)}else{const t=await Fs(void 0,p,G,20);h(t.data),a(x(t.data)),X(t.total_pages)}}catch(t){console.error("加载订单失败:",t)}finally{Z(!1)}};o.useEffect(()=>{a(x(r))},[r,b]);const V=(t,g)=>{if(g&&g.trim())return g;if(w[t])return w[t];const S=u.find(l=>{if(g&&l.item_title){const v=g.toLowerCase(),le=l.item_title.toLowerCase();return le.includes(v)||v.includes(le)}return!1});return S!=null&&S.item_title?S.item_title:"未知商品"},se=t=>{const g={};t.forEach(S=>{S.item_id&&(g[S.item_id]=S.item_title||S.item_id)}),I(g)};o.useEffect(()=>{y(),Ue().then(t=>{m(t),se(t)}).catch(t=>{console.error("加载商品列表失败:",t)})},[p,G,b]);const B=async()=>{Z(!0);try{const t=await da();await y(),t!=null&&t.message&&alert(t.message)}catch(t){console.error("同步订单失败:",t),alert((t==null?void 0:t.message)||"同步失败,请重试")}finally{Z(!1)}},pe=t=>{c(t),D(null),C(!0)},je=async t=>{var g;N(!0),D(null);try{const S=await xa([k],t),l=(g=S==null?void 0:S.results)==null?void 0:g[0];l!=null&&l.success?(D({success:!0,message:l.message}),y()):D({success:!1,message:(l==null?void 0:l.message)||"发货失败"})}catch(S){D({success:!1,message:(S==null?void 0:S.message)||"请求失败"})}finally{N(!1)}},he=t=>{$(t),te(!0)},we=t=>{z({...t}),F(!0)},Ce=async()=>{if(!(!d||!d.order_id))try{const t={};d.status!==void 0&&(t.order_status=d.status),d.buyer_id!==void 0&&(t.buyer_id=d.buyer_id),d.amount!==void 0&&(t.amount=d.amount),d.receiver_name!==void 0&&(t.receiver_name=d.receiver_name),d.receiver_phone!==void 0&&(t.receiver_phone=d.receiver_phone),d.receiver_address!==void 0&&(t.receiver_address=d.receiver_address),d.item_id!==void 0&&(t.item_id=d.item_id),d.quantity!==void 0&&(t.quantity=d.quantity),await ia(d.order_id,t),F(!1),z(null),y()}catch(t){console.error("更新订单失败:",t),alert("更新失败,请重试")}},Ne=async()=>{if(ee)try{const t=new FormData;t.append("file",ee),await ma(t),Q(!1),O(null),y(),alert("订单导入成功")}catch(t){alert((t==null?void 0:t.message)||"导入失败,请检查文件格式")}},ge=async t=>{P(t);t
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(V=>V.map(se=>`"${String(se).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),ne=new Blob(["\uFEFF"+ae],{type:"text/csv;charset=utf-8"}),x=URL.createObjectURL(ne),y=document.createElement("a");y.href=x,y.download="卡密组批量导入模板.csv",document.body.appendChild(y),y.click(),y.remove(),URL.revokeObjectURL(x)},D=async()=>{if(re){F(!0),te(null);try{const i=await ya(re);if(te(i),i.created>0){const P=await Ie();a(P)}}catch(i){te({error:(i==null?void 0:i.message)||"上传失败"})}finally{F(!1)}}},ee=async()=>{if(!(!L||!A.trim())){F(!0),z(null);try{const i=await fa(L,A);z({added:i.added}),$("");const P=await Ie();a(P)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{F(!1)}}},O=()=>{var i;X("create"),Z(null),te(null),Q((i=N[0])!=null&&i.id?String(N[0].id):""),$(""),z(null),M(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:O,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Je,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>m(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(De,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-8 py-5 w-[18%]",children:"卡密名称"}),e.jsx("th",{className:"px-6 py-5 w-[12%]",children:"卡密组ID"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"类型"}),e.jsx("th",{className:"px-6 py-5 w-[22%]",children:"内容/库存"}),e.jsx("th",{className:"px-6 py-5 w-[18%]",children:"描述"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),e.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(i=>{let P="";return i.type==="data"&&i.data_content?P=`库存: ${i.data_content.split(`
|
||||
`).filter(ne=>ne.trim()).length} 条`:i.type==="text"&&i.text_content?P=i.text_content.substring(0,20)+(i.text_content.length>20?"...":""):i.type==="api"&&i.api_config?P=i.api_config.url:i.type==="image"&&i.image_url&&(P="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-8 py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:e.jsx(H,{type:i.type})}),e.jsx("span",{className:"font-bold text-gray-900",children:i.name})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("button",{onClick:()=>j(i.id),className:"inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors",title:"复制卡密组ID,用于批量铺货表格",children:[i.id,e.jsx(_t,{className:"w-3.5 h-3.5"})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:P,children:P})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("button",{onClick:()=>c(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>J(i),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>C(i.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:e.jsx(Ae,{className:"w-5 h-5"})})]})})]},i.id)})})]})}),s.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Xs,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),r&&w&&ue.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>h(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(xe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:p.name||"",onChange:i=>W({...p,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:p.type||"text",onChange:i=>W({...p,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),e.jsx("option",{value:"api",children:"API接口"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),p.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:p.api_url||"",onChange:i=>W({...p,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:p.api_method||"GET",onChange:i=>W({...p,api_method:i.target.value}),className:"w-full ios-input px-4 py-Line truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:p.data_content?p.data_content.split(`
|
||||
`).filter(i=>i.trim()).length:0})," 条"]})]})]}),p.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:p.image_url||"",onChange:i=>W({...p,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),p.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:p.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:p.delay_seconds||0,onChange:i=>W({...p,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:p.description||"",onChange:i=>W({...p,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>W({...p,enabled:!p.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${p.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${p.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>h(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:U,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),u&&ue.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>m(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(xe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:b.name,onChange:i=>Y({...b,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(us,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ks,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),b.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:b.content.split(`
|
||||
`).filter(i=>i.trim()).length})," 条"]})]}),b.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:b.api_method,onChange:i=>Y({...b,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:b.api_timeout,onChange:i=>Y({...b,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:b.api_headers,onChange:i=>Y({...b,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:b.api_params,onChange:i=>Y({...b,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:b.description,onChange:i=>Y({...b,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:b.delay_seconds,onChange:i=>Y({...b,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>m(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:k,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),G&&ue.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>M(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(xe,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>X("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${E==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(kt,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>X("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${E==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Je,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),E==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:q,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),d&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",d.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>M(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),E==="create"?e.jsxs("button",{onClick:D,disabled:!re||T,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[T?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),T?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:ee,disabled:!L||!A.trim()||T||N.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[T?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(De,{className:"w-4 h-4"}),T?"处理中...":"追加卡密"]})]})]})}),document.body)]})},Ha=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},el=({onConfigureDelivery:s})=>{const[a,r]=o.useState([]),[h,u]=o.useState([]),[m,w]=o.useState([]),[I,p]=o.useState(""),[W,b]=o.useState(!1),[Y,G]=o.useState(!1),[M,E]=o.useState(!1),[X,re]=o.useState(!1),[Z,R]=o.useState(!1),[te,T]=o.useState(!1),[F,L]=o.useState(!1),[Q,A]=o.useState("upload"),[$,d]=o.useState(null),[z,H]=o.useState(null),[J,U]=o.useState(null),[C,k]=o.useState(null),[c,j]=o.useState(null),[N,q]=o.useState({}),[D,ee]=o.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[O,i]=o.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),P=async()=>{const l=await Ue();r(l)},ae=async()=>{u(await rs())};o.useEffect(()=>{Promise.all([js(),Ue(),rs()]).then(([l,v,le])=>{w(l),r(v),u(le)}).catch(l=>console.error("加载商品配置失败:",l))},[]),o.useEffect(()=>{if(!F||!(C!=null&&C.id)||C.status!=="running")return;const l=window.setInterval(async()=>{try{const v=await es(C.id);k(v),v.status!=="running"&&(A("done"),await P(),await ae())}catch(v){console.error("刷新批量铺货进度失败:",v)}},3e3);return()=>window.clearInterval(l)},[F,C==null?void 0:C.id,C==null?void 0:C.status]);const ne=async()=>{if(!I)return alert("请先选择账号");b(!0);try{const l=await ja(I);await P(),alert((l==null?void 0:l.message)||"商品同步完成")}catch(l){console.error("同步商品失败:",l),alert((l==null?void 0:l.message)||"同步失败,请重试")}finally{b(!1)}},x=l=>{j(l),q({...l}),re(!0)},y=async()=>{if(c)try{await $a(c.cookie_id,c.item_id,{item_title:N.item_title||"",item_description:N.item_description||"",item_category:N.item_category||"",item_price:N.item_price||"",item_detail:N.item_detail||c.item_detail||""}),await P(),await ae(),re(!1),j(null)}catch(l){console.error("更新商品失败:",l),alert("更新失败,请重试")}},V=async l=>{if(confirm(`确认删除商品"${l.item_title}"吗?`))try{await Na(l.cookie_id,l.item_id),r(v=>v.filter(le=>!(le.cookie_id===l.cookie_id&&le.item_id===l.item_id)))}catch(v){console.error("删除商品失败:",v),alert("删除失败,请重试")}},se=async()=>{try{if(!D.cookie_id||!D.item_id){alert("请选择账号并填写商品ID");return}await va(D.cookie_id,{item_id:D.item_id,item_title:D.item_title,item_price:D.item_price,item_detail:D.item_image?JSON.stringify({item_image:D.item_image}):""}),await P(),R(!1),ee({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(l){console.error("添加商品失败:",l),alert("添加失败,请重试")}},B=async()=>{if(!O.cookie_id)return alert("请选择发布账号");if(!O.title.trim())return alert("请填写商品标题");if(!O.price.trim())return alert("请填写商品价格");if(!O.quantity||Number(O.quantity)<=0)return alert("库存数量必须大于 0");if(O.images.length===0)return alert("至少上传 1 张商品图片");if(O.postage_mode==="fixed"&&!O.postage.trim())return alert("请填写一口价邮费");G(!0);try{const l=await wa(O);if(await P(),T(!1),i({cookie_id:I||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),l!=null&&l.item_id){const v={id:l.item_id,cookie_id:O.cookie_id,item_id:l.item_id,item_title:l.item_title||O.title,item_price:l.item_price||O.price,item_image:l.item_image};s(v),alert("商品发布成功,ID: "+l.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(l){console.error("发布商品失败:",l);const v=l==null?void 0:l.payload;if((v==null?void 0:v.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发
Line truncated
|
||||
`),$e=new Blob(["\uFEFF"+le],{type:"text/csv;charset=utf-8"}),Se=URL.createObjectURL($e),ve=document.createElement("a");ve.href=Se,ve.download="批量铺货模板.csv",document.body.appendChild(ve),ve.click(),ve.remove(),URL.revokeObjectURL(Se)},ge=()=>{ee(l=>({...l,cookie_id:I||l.cookie_id})),R(!0)},be=()=>{i(l=>({...l,cookie_id:I||l.cookie_id})),T(!0)},t=l=>h.filter(v=>v.cookie_id===l.cookie_id&&v.item_id===l.item_id),g=l=>{switch(l){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return l||"-"}},S=l=>{switch(l){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:I,onChange:l=>p(l.target.value),children:[e.jsx("option",{value:"",children:"选择账号以同步"}),m.map(l=>e.jsx("option",{value:l.id,children:l.nickname},l.id))]}),e.jsxs("button",{onClick:ne,disabled:W||!I,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(ke,{className:`w-4 h-4 ${W?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ge,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(De,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:be,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(os,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:pe,className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Ze,{className:"w-4 h-4"}),"批量铺货"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[a.map(l=>{const v=t(l),le=v.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>x(l),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>V(l),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(Ae,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[l.item_image?e.jsx("img",{src:l.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Gs,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:Ha(l.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:l.item_title}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",l.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${le?"text-emerald-600":"text-amber-600"}`,children:[le?e.jsx(et,{className:"w-3 h-3"}):e.jsx(St,{className:"w-3 h-3"}),le?`${v.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(l),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${le?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100Line truncated
|
||||
@@ -0,0 +1,19 @@
|
||||
import{j as e,r as d,b as he,c as bt,d as yt}from"./react-vendor-DZnRGM0-.js";import{L as ft,U as Ks,S as Gs,C as us,B as Xs,Z as hs,a as Be,b as ys,c as Zs,d as jt,A as ws,D as Nt,e as _s,P as Hs,f as Xe,E as et,T as vt,g as ke,Q as is,h as gs,i as Ae,j as qe,k as ls,l as ks,R as Se,m as st,n as wt,o as De,X as pe,K as _t,p as Ge,q as ze,r as Le,s as Pe,t as Ss,u as kt,v as Ue,w as St,x as Ct,y as Ke,z as $t,F as Cs,I as $s,G as Is,H as It,J as At,M as os,N as Ze,O as tt,V as Dt,W as Pt,Y as bs,_ as Lt,$ as Ft,a0 as As,a1 as Et,a2 as at,a3 as as,a4 as lt,a5 as Rt,a6 as Ot,a7 as fs,a8 as rt,a9 as Tt,aa as Mt}from"./icons-vendor-BmeuAUrP.js";import{R as He,B as qt,X as Ds,Y as Ps,T as ds,a as Bt,C as cs,A as zt,b as Ut,c as Wt,P as Ls,d as Fs,L as Jt}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const g of document.querySelectorAll('link[rel="modulepreload"]'))h(g);new MutationObserver(g=>{for(const p of g)if(p.type==="childList")for(const k of p.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&h(k)}).observe(document,{childList:!0,subtree:!0});function l(g){const p={};return g.integrity&&(p.integrity=g.integrity),g.referrerPolicy&&(p.referrerPolicy=g.referrerPolicy),g.crossOrigin==="use-credentials"?p.credentials="include":g.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function h(g){if(g.ep)return;g.ep=!0;const p=l(g);fetch(g.href,p)}})();const Vt=({activeTab:s,isAdmin:a=!1,onNavigate:l,onLogout:h})=>{const g=[{id:"dashboard",icon:ft,label:"仪表盘"},{id:"accounts",icon:Ks,label:"账号管理"},{id:"orders",icon:Gs,label:"订单管理"},{id:"cards",icon:us,label:"卡密库存"},{id:"items",icon:Xs,label:"商品列表"},{id:"rules",icon:hs,label:"自动化规则"},{id:"notifications",icon:Be,label:"通知设置"},...a?[{id:"settings",icon:ys,label:"系统与AI"}]:[]];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:g.map(p=>{const k=p.icon,_=s===p.id;return e.jsxs("button",{onClick:()=>l(p.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${_?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(k,{className:`w-5 h-5 transition-colors ${_?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:p.label}),_&&e.jsx(Zs,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},p.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:h,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(jt,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Qt=s=>{if(!s)return"";const a=new URLSearchParams;for(const[h,g]of Object.entries(s))g!=null&&a.set(h,String(g));const l=a.toString();return l?`?${l}`:""},ns=async(s,a,l={})=>{const h=Qt(l.params),g=`${a}${h}`,p=await fetch(g,{method:s,credentials:"include",headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)}),_=(p.headers.get("content-type")||"").includes("application/json");if(!p.ok){const u=_?await p.json().catch(()=>{}):await p.text().catch(()=>{}),q=typeof u=="string"?u:(u==null?void 0:u.detail)||(u==null?void 0:u.message)||(u==null?void 0:u.msg);throw new Error(q||`请求失败: ${p.status}`)}return _?await p.json():await p.text()},me=async(s,a)=>ns("GET",s,{params:a}),de=async(s,a)=>ns("POST",s,{body:a}),Ne=async(s,a)=>ns("PUT",s,{body:a}),Oe=async(s,a)=>ns("DELETE",s,{params:a}),js=async(s,a)=>{const l=await fetch(s,{method:"POST",credentials:"include",body:a}),p=(l.headers.get("content-type")||"").includes("application/json")?await l.json().catch(()=>{}):await l.text().catch(()=>{});if(!l.ok){const k=typeof p=="string"?p:(p==null?void 0:p.detail)||(p==null?void 0:p.message)||(p==null?void 0:p.msg),_=new Error(k||"请求失败: "+l.staLine truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(ys,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>F(null),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:P,children:"取消"}),e.jsxs("button",{onClick:Ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:P,children:[P?e.jsx(ke,{className:"w-4 h-4 animate-spin"}):e.jsx(Le,{className:"w-4 h-4"}),P?"保存中...":"保存"]})]})})]})}),document.body)]})},zs=({status:s})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[s]||a.cancelled}`,children:l[s]||s})},al=()=>{const[s,a]=d.useState([]),[l,h]=d.useState([]),[g,p]=d.useState([]),[k,_]=d.useState({}),[u,q]=d.useState("all"),[b,Y]=d.useState(""),[te,B]=d.useState(1),[Q,T]=d.useState(1),[Z,H]=d.useState(!1),[E,X]=d.useState(!1),[ee,I]=d.useState(!1),[J,U]=d.useState(!1),[v,F]=d.useState(null),[o,C]=d.useState(null),[re,K]=d.useState({}),[z,S]=d.useState(!1),[A,W]=d.useState(""),[m,x]=d.useState(!1),[P,N]=d.useState(null),[se,D]=d.useState(null),[i,R]=d.useState(null),[ne,ae]=d.useState(null),c=t=>{if(!b.trim())return t;const y=b.toLowerCase().trim();return t.filter($=>{var O,oe,r,L,ie,$e;return((O=$.order_id)==null?void 0:O.toLowerCase().includes(y))||((oe=$.item_id)==null?void 0:oe.toLowerCase().includes(y))||((r=$.buyer_id)==null?void 0:r.toLowerCase().includes(y))||((L=$.item_title)==null?void 0:L.toLowerCase().includes(y))||((ie=$.receiver_name)==null?void 0:ie.toLowerCase().includes(y))||(($e=$.receiver_phone)==null?void 0:$e.toLowerCase().includes(y))})},f=async()=>{H(!0);try{if(b.trim()){let t=[],y=1,$=!0;for(;$;){const O=await Rs(void 0,u,y,100);t=[...t,...O.data],$=y<O.total_pages,y++}h(t),a(c(t)),T(1)}else{const t=await Rs(void 0,u,te,20);h(t.data),a(c(t.data)),T(t.total_pages)}}catch(t){console.error("加载订单失败:",t)}finally{H(!1)}};d.useEffect(()=>{a(c(l))},[l,b]);const V=(t,y)=>{if(y&&y.trim())return y;if(k[t])return k[t];const $=g.find(O=>{if(y&&O.item_title){const oe=y.toLowerCase(),r=O.item_title.toLowerCase();return r.includes(oe)||oe.includes(r)}return!1});return $!=null&&$.item_title?$.item_title:"未知商品"},le=t=>{const y={};t.forEach($=>{$.item_id&&(y[$.item_id]=$.item_title||$.item_id)}),_(y)};d.useEffect(()=>{f(),We().then(t=>{p(t),le(t)}).catch(t=>{console.error("加载商品列表失败:",t)})},[u,te,b]);const M=async()=>{H(!0);try{const t=await pa();await f(),t!=null&&t.message&&alert(t.message)}catch(t){console.error("同步订单失败:",t),alert((t==null?void 0:t.message)||"同步失败,请重试")}finally{H(!1)}},ge=t=>{W(t),N(null),S(!0)},ve=async t=>{var y;x(!0),N(null);try{const $=await ha([A],t),O=(y=$==null?void 0:$.results)==null?void 0:y[0];O!=null&&O.success?(N({success:!0,message:O.message}),f()):N({success:!1,message:(O==null?void 0:O.message)||"发货失败"})}catch($){N({success:!1,message:($==null?void 0:$.message)||"请求失败"})}finally{x(!1)}},be=t=>{F(t),X(!0)},_e=t=>{C({...t}),I(!0)},Ce=async()=>{if(!(!o||!o.order_id))try{const t={};o.status!==void 0&&(t.order_status=o.status),o.buyer_id!==void 0&&(t.buyer_id=o.buyer_id),o.amount!==void 0&&(t.amount=o.amount),o.receiver_name!==void 0&&(t.receiver_name=o.receiver_name),o.receiver_phone!==void 0&&(t.receiver_phone=o.receiver_phone),o.receiver_address!==void 0&&(t.receiver_address=o.receiver_address),o.item_id!==void 0&&(t.item_id=o.item_id),o.quantity!==void 0&&(t.quantity=o.quantity),await xa(o.order_id,t),I(!1),C(null),f()}catch(t){console.error("更新订单失败:",t),alert("更新失败,请重试")}},we=async()=>{if(se)try{const t=new FormData;t.append("file",se),await ga(t),U(!1),D(null),f(),alert("订单导入成功")}catch(t){alert((t==null?void 0:t.message)||"导入失败,请检查文件格式")}},ye=async t=>{R(t);tr
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(V=>V.map(le=>`"${String(le).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),ae=new Blob(["\uFEFF"+ne],{type:"text/csv;charset=utf-8"}),c=URL.createObjectURL(ae),f=document.createElement("a");f.href=c,f.download="卡密组批量导入模板.csv",document.body.appendChild(f),f.click(),f.remove(),URL.revokeObjectURL(c)},N=async()=>{if(Z){I(!0),X(null);try{const i=await va(Z);if(X(i),i.created>0){const R=await Ie();a(R)}}catch(i){X({error:(i==null?void 0:i.message)||"上传失败"})}finally{I(!1)}}},se=async()=>{if(!(!J||!v.trim())){I(!0),C(null);try{const i=await wa(J,v);C({added:i.added}),F("");const R=await Ie();a(R)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{I(!1)}}},D=()=>{var i;T("create"),H(null),X(null),U((i=x[0])!=null&&i.id?String(x[0].id):""),F(""),C(null),B(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:D,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Ke,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>p(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Pe,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-8 py-5 w-[18%]",children:"卡密名称"}),e.jsx("th",{className:"px-6 py-5 w-[12%]",children:"卡密组ID"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"类型"}),e.jsx("th",{className:"px-6 py-5 w-[22%]",children:"内容/库存"}),e.jsx("th",{className:"px-6 py-5 w-[18%]",children:"描述"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),e.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(i=>{let R="";return i.type==="data"&&i.data_content?R=`库存: ${i.data_content.split(`
|
||||
`).filter(ae=>ae.trim()).length} 条`:i.type==="text"&&i.text_content?R=i.text_content.substring(0,20)+(i.text_content.length>20?"...":""):i.type==="api"&&i.api_config?R=i.api_config.url:i.type==="image"&&i.image_url&&(R="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-8 py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:e.jsx(re,{type:i.type})}),e.jsx("span",{className:"font-bold text-gray-900",children:i.name})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("button",{onClick:()=>m(i.id),className:"inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors",title:"复制卡密组ID,用于批量铺货表格",children:[i.id,e.jsx($t,{className:"w-3.5 h-3.5"})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:R,children:R})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("button",{onClick:()=>W(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>K(i),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(Ue,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>S(i.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:e.jsx(De,{className:"w-5 h-5"})})]})})]},i.id)})})]})}),s.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Hs,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),l&&k&&he.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>h(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(pe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:u.name||"",onChange:i=>q({...u,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:u.type||"text",onChange:i=>q({...u,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),e.jsx("option",{value:"api",children:"API接口"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),u.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:u.api_url||"",onChange:i=>q({...u,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:u.api_method||"GET",onChange:i=>q({...u,api_method:i.target.value}),className:"w-full ios-input px-4 pyLine truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:u.data_content?u.data_content.split(`
|
||||
`).filter(i=>i.trim()).length:0})," 条"]})]})]}),u.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:u.image_url||"",onChange:i=>q({...u,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),u.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:u.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:u.delay_seconds||0,onChange:i=>q({...u,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:u.description||"",onChange:i=>q({...u,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>q({...u,enabled:!u.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${u.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${u.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>h(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:z,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),g&&he.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>p(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(pe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:b.name,onChange:i=>Y({...b,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(us,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Cs,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),b.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:b.content.split(`
|
||||
`).filter(i=>i.trim()).length})," 条"]})]}),b.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:b.api_method,onChange:i=>Y({...b,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:b.api_timeout,onChange:i=>Y({...b,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:b.api_headers,onChange:i=>Y({...b,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:b.api_params,onChange:i=>Y({...b,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:b.description,onChange:i=>Y({...b,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:b.delay_seconds,onChange:i=>Y({...b,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>p(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:A,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),te&&he.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>B(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(pe,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>T("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${Q==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(It,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>T("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${Q==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ke,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),Q==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:P,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),o&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",o.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>B(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),Q==="create"?e.jsxs("button",{onClick:N,disabled:!Z||ee,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[ee?e.jsx(ke,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),ee?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:se,disabled:!J||!v.trim()||ee||x.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[ee?e.jsx(ke,{className:"w-4 h-4 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4"}),ee?"处理中...":"追加卡密"]})]})]})}),document.body)]})},rl=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},nl=({onConfigureDelivery:s})=>{const[a,l]=d.useState([]),[h,g]=d.useState([]),[p,k]=d.useState([]),[_,u]=d.useState(""),[q,b]=d.useState(!1),[Y,te]=d.useState(!1),[B,Q]=d.useState(!1),[T,Z]=d.useState(!1),[H,E]=d.useState(!1),[X,ee]=d.useState(!1),[I,J]=d.useState(!1),[U,v]=d.useState("upload"),[F,o]=d.useState(null),[C,re]=d.useState(null),[K,z]=d.useState(null),[S,A]=d.useState(null),[W,m]=d.useState(null),[x,P]=d.useState({}),[N,se]=d.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[D,i]=d.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[R,ne]=d.useState([]);d.useEffect(()=>{if(!X||D.images.length===0){ne([]);return}const r=D.images.map((L,ie)=>({key:L.name+ie,url:URL.createObjectURL(L)}));return ne(r),()=>{r.forEach(L=>URL.revokeObjectURL(L.url))}},[X,D.images]);const ae=async()=>{const r=await We();l(r)},c=async()=>{g(await rs())};d.useEffect(()=>{Promise.all([Ns(),We(),rs()]).then(([r,L,ie])=>{k(r),l(L),g(ie)}).catch(r=>console.error("加载商品配置失败:",r))},[]),d.useEffect(()=>{if(!I||!(S!=null&&S.id)||S.status!=="running")return;const r=window.setInterval(async()=>{try{const L=await es(S.id);A(L),L.status!=="running"&&(v("done"),await ae(),await c())}catch(L){console.error("刷新批量铺货进度失败:",L)}},3e3);return()=>window.clearInterval(r)},[I,S==null?void 0:S.id,S==null?void 0:S.status]);const f=async()=>{if(!_)return alert("请先选择账号");b(!0);try{const r=await _a(_);await ae(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{b(!1)}},V=r=>{m(r),P({...r}),Z(!0)},le=async()=>{if(W)try{await Pa(W.cookie_id,W.item_id,{item_title:x.item_title||"",item_description:x.item_description||"",item_category:x.item_category||"",item_price:x.item_price||"",item_detail:x.item_detail||W.item_detail||""}),await ae(),await c(),Z(!1),m(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},M=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await ka(r.cookie_id,r.item_id),l(L=>L.filter(ie=>!(ie.cookie_id===r.cookie_id&&ie.item_id===r.item_id)))}catch(L){console.error("删除商品失败:",L),alert("删除失败,请重试")}},ge=async()=>{try{if(!N.cookie_id||!N.item_id){alert("请选择账号并填写商品ID");return}await Sa(N.cookie_id,{item_id:N.item_id,item_title:N.item_title,item_price:N.item_price,item_detail:N.item_image?JSON.stringify({item_image:N.item_image}):""}),await ae(),E(!1),se({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},ve=async()=>{if(!D.cookie_id)return alert("请选择发布账号");if(!D.title.trim())return alert("请填写商品标题");if(!D.price.trim())return alert("请填写商品价格");if(!D.quantity||Number(D.quantity)<=0)return alert("库存数量必须大于 0");if(D.images.length===0)return alert("至少上传 1 张商品图片");if(D.postage_mode==="fixed"&&!D.postage.trim())return alert("请填写一口价邮费");te(!0);try{const r=await Ca(D);if(await ae(),ee(!1),i({cookie_id:_||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),r!=null&&r.item_id){const L={id:r.item_id,cookie_id:D.cookie_id,item_id:r.item_id,item_title:r.item_title||D.title,item_price:r.item_price||D.price,item_image:r.item_image};s(L),alert("商品发布成功,ID: "+r.item_id+",已为
Line truncated
|
||||
`),$e=new Blob(["\uFEFF"+ie],{type:"text/csv;charset=utf-8"}),Je=URL.createObjectURL($e),Fe=document.createElement("a");Fe.href=Je,Fe.download="批量铺货模板.csv",document.body.appendChild(Fe),Fe.click(),Fe.remove(),URL.revokeObjectURL(Je)},t=()=>{se(r=>({...r,cookie_id:_||r.cookie_id})),E(!0)},y=()=>{i(r=>({...r,cookie_id:_||r.cookie_id})),ee(!0)},$=r=>h.filter(L=>L.cookie_id===r.cookie_id&&L.item_id===r.item_id),O=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},oe=r=>{switch(r){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:_,onChange:r=>u(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号以同步"}),p.map(r=>e.jsx("option",{value:r.id,children:r.nickname},r.id))]}),e.jsxs("button",{onClick:f,disabled:q||!_,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Se,{className:`w-4 h-4 ${q?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:t,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Pe,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:y,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(os,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:be,className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Ze,{className:"w-4 h-4"}),"批量铺货"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[a.map(r=>{const L=$(r),ie=L.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>V(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(Ue,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>M(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(De,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[r.item_image?e.jsx("img",{src:r.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Xs,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:rl(r.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:r.item_title}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",r.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${ie?"text-emerald-600":"text-amber-600"}`,children:[ie?e.jsx(tt,{className:"w-3 h-3"}):e.jsx(Dt,{className:"w-3 h-3"}),ie?`${L.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(r),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${ie?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100"}`Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{rigLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{rigLine truncated
|
||||
@@ -6,12 +6,12 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
|
||||
<script type="module" crossorigin src="/static/assets/index-BVGBdlzO.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-BcWGTs2i.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-DZnRGM0-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BmeuAUrP.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/vendor-w5t2K9ux.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-B_BfwiL0.js">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-DgV81f94.css">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-D71nKbMO.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -73,6 +73,15 @@ type RefreshResult struct {
|
||||
UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同)
|
||||
}
|
||||
|
||||
// FreshCaptchaResult 是重取 token 风控验证链接的结果。
|
||||
type FreshCaptchaResult struct {
|
||||
TokenOK bool
|
||||
AccessToken string
|
||||
UpdatedCookies string
|
||||
VerificationURL string
|
||||
Ret []string
|
||||
}
|
||||
|
||||
// UserProfileResult 是 mtop.idle.web.user.page.nav 返回的当前账号资料。
|
||||
type UserProfileResult struct {
|
||||
Nickname string
|
||||
|
||||
@@ -59,6 +59,28 @@ func (c *ClientImpl) RefreshTokenWithDeviceIDContext(ctx context.Context, cookie
|
||||
return &RefreshResult{UpdatedCookies: currentCookies}, fmt.Errorf("token API 登录凭证已失效")
|
||||
}
|
||||
|
||||
// RequestFreshCaptchaURLContext 重新请求 token API,用于浏览器风控验证前获取新鲜验证链接。
|
||||
// 如果风控已解除并直接返回 accessToken,则 TokenOK=true。
|
||||
func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*FreshCaptchaResult, error) {
|
||||
accessToken, ret, updatedCookies, verificationURL, _, err := c.refreshTokenOnce(ctx, cookiesStr, deviceID)
|
||||
if err != nil {
|
||||
return &FreshCaptchaResult{UpdatedCookies: updatedCookies}, err
|
||||
}
|
||||
if accessToken != "" {
|
||||
return &FreshCaptchaResult{
|
||||
TokenOK: true,
|
||||
AccessToken: accessToken,
|
||||
UpdatedCookies: updatedCookies,
|
||||
Ret: ret,
|
||||
}, nil
|
||||
}
|
||||
return &FreshCaptchaResult{
|
||||
UpdatedCookies: updatedCookies,
|
||||
VerificationURL: verificationURL,
|
||||
Ret: ret,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string) (string, []string, string, string, int, error) {
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
|
||||
Reference in new issue
Block a user