feat: 对齐闲鱼续期流程并完善业务管理
对齐官方 WebSocket 批量握手、注册、心跳、ACK、同步恢复及运行时设备标识生命周期。 保留 Cookie 完整属性,接入静默续期和保存登录信息设置,并在凭证更新后重建账号连接。 完善订单与商品同步、卡券和通知渠道交互,更新前端品牌、时间展示及嵌入资源。 补充 Go 与前端回归测试,确保完整检查和生产构建通过。
This commit is contained in:
1 parent
3cc1d4094d
commit
d77c317452
69 files changed
+3169
-819
No files matched your search
+5
-4
@@ -8,6 +8,7 @@ import ItemList from './components/ItemList';
|
||||
import Settings from './components/Settings';
|
||||
import Rules from './components/Rules';
|
||||
import Notifications from './components/Notifications';
|
||||
import { YdisksBrandIcon } from './components/YdisksLogo';
|
||||
import { login, logout, verifySession } from './services/api';
|
||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
||||
|
||||
@@ -157,8 +158,8 @@ const App: React.FC = () => {
|
||||
|
||||
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in">
|
||||
<div className="text-center mb-8">
|
||||
<div className="w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 p-4" style={{ filter: 'drop-shadow(0 8px 20px rgba(0,148,247,0.3))' }}>
|
||||
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full" />
|
||||
<div className="mx-auto mb-6 flex justify-center">
|
||||
<YdisksBrandIcon sizeClass="w-24 h-24" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">系统尚未初始化</h2>
|
||||
<p className="text-gray-600 font-medium">为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。</p>
|
||||
@@ -202,8 +203,8 @@ const App: React.FC = () => {
|
||||
|
||||
{/* Header with Logo */}
|
||||
<div className="text-center mb-10">
|
||||
<div className="w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 cursor-pointer group p-4" style={{ filter: 'drop-shadow(0 8px 20px rgba(0,148,247,0.3))' }}>
|
||||
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full group-hover:scale-110 transition-transform" />
|
||||
<div className="group mx-auto mb-6 flex cursor-pointer justify-center">
|
||||
<YdisksBrandIcon sizeClass="w-24 h-24" logoClassName="w-full h-full text-white group-hover:scale-110 transition-transform" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">欢迎回来</h2>
|
||||
<p className="text-gray-500 font-medium">Ydisks闲鱼助手 · 自动发货与管家系统</p>
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
getAccountAISettings,
|
||||
getNotificationChannels,
|
||||
getAccountBindings,
|
||||
getLongLoginSettings,
|
||||
setLongLoginSettings,
|
||||
} from '../services/api';
|
||||
import { shouldUpdateAccountPause } from './accountPause';
|
||||
import {
|
||||
@@ -49,6 +51,7 @@ const AccountList: React.FC = () => {
|
||||
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
|
||||
const [activeModal, setActiveModal] = useState<ModalType>(null);
|
||||
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
|
||||
const [longLogin, setLongLogin] = useState({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
|
||||
// 通知渠道绑定(编辑弹窗用)
|
||||
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
|
||||
@@ -328,7 +331,28 @@ const AccountList: React.FC = () => {
|
||||
clear_password: false,
|
||||
});
|
||||
setActiveModal('edit');
|
||||
await loadNotificationBindings(account.id);
|
||||
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
const [, longLoginResult] = await Promise.allSettled([
|
||||
loadNotificationBindings(account.id),
|
||||
getLongLoginSettings(account.id),
|
||||
]);
|
||||
if (longLoginResult.status === 'fulfilled') {
|
||||
setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' });
|
||||
} else {
|
||||
setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' });
|
||||
}
|
||||
};
|
||||
|
||||
const handleLongLoginToggle = async () => {
|
||||
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
|
||||
const enabled = !longLogin.enabled;
|
||||
setLongLogin(current => ({ ...current, saving: true, error: '' }));
|
||||
try {
|
||||
const result = await setLongLoginSettings(editingAccount.id, enabled);
|
||||
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
|
||||
} catch (error) {
|
||||
setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
|
||||
}
|
||||
};
|
||||
|
||||
const openAIModal = async (account: AccountDetail) => {
|
||||
@@ -966,6 +990,22 @@ const AccountList: React.FC = () => {
|
||||
登录信息
|
||||
</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4">
|
||||
<div>
|
||||
<div className="font-bold text-gray-900">保存登录信息</div>
|
||||
<div className="mt-1 text-xs text-gray-500">状态直接读取并修改闲鱼官方长登录设置</div>
|
||||
{longLogin.error && <div className="mt-1 text-xs text-red-600">{longLogin.error}</div>}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="保存登录信息"
|
||||
disabled={longLogin.loading || longLogin.saving || !longLogin.canOpen}
|
||||
onClick={() => void handleLongLoginToggle()}
|
||||
className={`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${longLogin.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||
>
|
||||
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${longLogin.enabled ? 'translate-x-6' : 'translate-x-0'}`} />
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">用户名</label>
|
||||
<input
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Card } from '../types';
|
||||
import { getCards, createCard, updateCard, deleteCard, batchCreateCards, appendCardData } from '../services/api';
|
||||
import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, FileDown, ListPlus } from 'lucide-react';
|
||||
import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, FileDown, ListPlus, Search, SlidersHorizontal } from 'lucide-react';
|
||||
import { filterCards } from './cardListState';
|
||||
|
||||
type AddCardForm = {
|
||||
name: string;
|
||||
@@ -55,6 +56,8 @@ const CardList: React.FC = () => {
|
||||
const [appendTargetId, setAppendTargetId] = useState<string>('');
|
||||
const [appendContent, setAppendContent] = useState('');
|
||||
const [appendResult, setAppendResult] = useState<{ added: number } | null>(null);
|
||||
const [typeFilter, setTypeFilter] = useState<Card['type'] | ''>('');
|
||||
const [nameSearch, setNameSearch] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
getCards().then(setCards);
|
||||
@@ -213,6 +216,10 @@ const CardList: React.FC = () => {
|
||||
};
|
||||
|
||||
const dataCards = cards.filter(c => c.type === 'data');
|
||||
const filteredCards = useMemo(
|
||||
() => filterCards(cards, typeFilter, nameSearch),
|
||||
[cards, nameSearch, typeFilter],
|
||||
);
|
||||
|
||||
const downloadCardTemplate = () => {
|
||||
const headers = ['名称', '类型', '内容', '描述', '启用', '延迟秒', '多规格', '规格名', '规格值'];
|
||||
@@ -306,28 +313,61 @@ const CardList: React.FC = () => {
|
||||
</div>
|
||||
|
||||
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
|
||||
<div className="flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-1 flex-col gap-3 sm:flex-row">
|
||||
<div className="relative sm:w-48">
|
||||
<SlidersHorizontal className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<select
|
||||
aria-label="按卡密类型筛选"
|
||||
value={typeFilter}
|
||||
onChange={event => setTypeFilter(event.target.value as Card['type'] | '')}
|
||||
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm"
|
||||
>
|
||||
<option value="">全部类型</option>
|
||||
<option value="data">批量卡密</option>
|
||||
<option value="text">文本</option>
|
||||
<option value="api">API</option>
|
||||
<option value="image">图片</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="relative w-full sm:max-w-sm">
|
||||
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="search"
|
||||
aria-label="按卡密名称搜索"
|
||||
placeholder="搜索卡密名称..."
|
||||
value={nameSearch}
|
||||
onChange={event => setNameSearch(event.target.value)}
|
||||
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="whitespace-nowrap px-1 text-xs font-bold text-gray-400">
|
||||
显示 {filteredCards.length} / {cards.length} 组
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<table className="w-full table-fixed text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50">
|
||||
<th className="px-8 py-5 w-[18%]">卡密名称</th>
|
||||
<th className="px-6 py-5 w-[12%]">卡密组ID</th>
|
||||
<th className="px-6 py-5 w-[10%]">类型</th>
|
||||
<th className="px-6 py-5 w-[22%]">内容/库存</th>
|
||||
<th className="px-6 py-5 w-[18%]">描述</th>
|
||||
<th className="px-6 py-5 w-[10%]">状态</th>
|
||||
<th className="px-6 py-5 w-[10%] text-right">操作</th>
|
||||
<th className="w-[23%] px-5 py-5">卡密名称</th>
|
||||
<th className="w-[8%] px-3 py-5">卡密组ID</th>
|
||||
<th className="w-[7%] px-2 py-5">类型</th>
|
||||
<th className="w-[27%] px-5 py-5">内容/库存</th>
|
||||
<th className="w-[19%] px-5 py-5">描述</th>
|
||||
<th className="w-[7%] px-2 py-5">状态</th>
|
||||
<th className="w-[9%] px-3 py-5 text-right">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-50">
|
||||
{cards.map((card) => {
|
||||
{filteredCards.map((card) => {
|
||||
// 计算库存或内容预览
|
||||
let stockInfo = '';
|
||||
if (card.type === 'data' && card.data_content) {
|
||||
const lines = card.data_content.split('\n').filter(line => line.trim());
|
||||
stockInfo = `库存: ${lines.length} 条`;
|
||||
} else if (card.type === 'text' && card.text_content) {
|
||||
stockInfo = card.text_content.substring(0, 20) + (card.text_content.length > 20 ? '...' : '');
|
||||
stockInfo = card.text_content;
|
||||
} else if (card.type === 'api' && card.api_config) {
|
||||
stockInfo = card.api_config.url;
|
||||
} else if (card.type === 'image' && card.image_url) {
|
||||
@@ -336,26 +376,26 @@ const CardList: React.FC = () => {
|
||||
|
||||
return (
|
||||
<tr key={card.id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
|
||||
<td className="px-8 py-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors">
|
||||
<td className="px-5 py-5 align-middle">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white">
|
||||
<CardIcon type={card.type} />
|
||||
</div>
|
||||
<span className="font-bold text-gray-900">{card.name}</span>
|
||||
<span className="line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900" title={card.name}>{card.name}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<td className="px-3 py-5">
|
||||
<button
|
||||
onClick={() => copyCardID(card.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"
|
||||
className="inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200"
|
||||
title="复制卡密组ID,用于批量铺货表格"
|
||||
>
|
||||
{card.id}
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
<span className="truncate">{card.id}</span>
|
||||
<Copy className="h-3 w-3 shrink-0" />
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<span className={`px-3 py-1.5 rounded-lg text-xs font-bold ${
|
||||
<td className="px-2 py-5">
|
||||
<span className={`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${
|
||||
card.type === 'text' ? 'bg-blue-50 text-blue-600' :
|
||||
card.type === 'data' ? 'bg-purple-50 text-purple-600' :
|
||||
card.type === 'api' ? 'bg-blue-50 text-blue-600' :
|
||||
@@ -366,20 +406,20 @@ const CardList: React.FC = () => {
|
||||
card.type === 'api' ? 'API' : '图片'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<span className="text-sm text-gray-600 font-mono block truncate" title={stockInfo}>
|
||||
<td className="px-5 py-5">
|
||||
<span className="line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600" title={stockInfo}>
|
||||
{stockInfo}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<td className="px-5 py-5">
|
||||
<span
|
||||
className="text-sm text-gray-500 block max-w-[200px] truncate"
|
||||
className="block truncate text-sm text-gray-500"
|
||||
title={card.description || '-'}
|
||||
>
|
||||
{card.description || '-'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<td className="px-2 py-5">
|
||||
<button
|
||||
onClick={() => toggleCardStatus(card)}
|
||||
className={`w-12 h-8 rounded-full relative transition-colors ${
|
||||
@@ -391,20 +431,20 @@ const CardList: React.FC = () => {
|
||||
}`}></div>
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<td className="px-3 py-5">
|
||||
<div className="flex items-center justify-end gap-0.5">
|
||||
<button
|
||||
onClick={() => handleEdit(card)}
|
||||
className="p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors"
|
||||
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black"
|
||||
title="编辑"
|
||||
>
|
||||
<Edit className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(card.id)}
|
||||
className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors"
|
||||
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
||||
>
|
||||
<Trash2 className="w-5 h-5" />
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
@@ -415,10 +455,10 @@ const CardList: React.FC = () => {
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{cards.length === 0 && (
|
||||
{filteredCards.length === 0 && (
|
||||
<div className="py-20 text-center text-gray-400">
|
||||
<Package className="w-12 h-12 mx-auto mb-4 opacity-30" />
|
||||
<p>暂无卡密配置,请点击右上角添加。</p>
|
||||
<p>{cards.length === 0 ? '暂无卡密配置,请点击右上角添加。' : '没有符合当前筛选条件的卡密组。'}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from 'react';
|
||||
import { DashboardStats, OrderAnalytics, Order, OrderStatus, Item } from '../types';
|
||||
import { getDashboardStats, getOrderAnalytics, getValidOrders, getItems } from '../services/api';
|
||||
import { getDateRange, getPreviousDateRange, TimeRange } from '../dateRange';
|
||||
import { formatLocalDateTime } from '../dateTime';
|
||||
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
|
||||
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend } from 'recharts';
|
||||
|
||||
@@ -588,7 +589,7 @@ const Dashboard: React.FC = () => {
|
||||
<td className="px-6 py-4">
|
||||
<div className="text-sm font-bold text-gray-800">{order.buyer_id}</div>
|
||||
{order.created_at && (
|
||||
<div className="text-xs text-gray-400 mt-1">{order.created_at}</div>
|
||||
<div className="text-xs text-gray-400 mt-1">{formatLocalDateTime(order.created_at)}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { selectActivePublishBatch } from './itemPublishBatchState';
|
||||
import { Item, AccountDetail, ShippingRule } from '../types';
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
deleteItem,
|
||||
getShippingRules
|
||||
} from '../services/api';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, X } from 'lucide-react';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
|
||||
|
||||
interface ItemListProps {
|
||||
onConfigureDelivery: (item: Item) => void;
|
||||
@@ -77,6 +77,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const [shippingRules, setShippingRules] = useState<ShippingRule[]>([]);
|
||||
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||
const [selectedAccount, setSelectedAccount] = useState<string>('');
|
||||
const [accountFilter, setAccountFilter] = useState<string>('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
@@ -510,24 +511,72 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
}
|
||||
};
|
||||
|
||||
const accountMap = useMemo(
|
||||
() => new Map(accounts.map(account => [account.id, account])),
|
||||
[accounts],
|
||||
);
|
||||
const visibleItems = useMemo(
|
||||
() => accountFilter ? items.filter(item => item.cookie_id === accountFilter) : items,
|
||||
[accountFilter, items],
|
||||
);
|
||||
const accountName = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
const name = account?.remark || account?.nickname;
|
||||
return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
|
||||
};
|
||||
const accountNickname = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
return account?.remark || account?.nickname || '未命名账号';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-fade-in">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-gray-900">商品管理</h2>
|
||||
<p className="text-gray-500 mt-2 text-sm">监控并管理所有账号下的闲鱼商品。</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<select
|
||||
className="ios-input px-4 py-3 rounded-xl text-sm"
|
||||
value={selectedAccount}
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
>
|
||||
<option value="">选择账号以同步</option>
|
||||
{accounts.map(acc => (
|
||||
<option key={acc.id} value={acc.id}>{acc.nickname}</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="flex min-w-[200px] flex-col gap-1.5">
|
||||
<label htmlFor="item-account-filter" className="px-1 text-[11px] font-extrabold tracking-wide text-gray-500">
|
||||
商品列表筛选
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Filter className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<select
|
||||
id="item-account-filter"
|
||||
aria-label="按账号筛选商品列表"
|
||||
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
|
||||
value={accountFilter}
|
||||
onChange={event => setAccountFilter(event.target.value)}
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-w-[200px] flex-col gap-1.5">
|
||||
<label htmlFor="item-sync-account" className="px-1 text-[11px] font-extrabold tracking-wide text-gray-500">
|
||||
同步商品账号
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<select
|
||||
id="item-sync-account"
|
||||
aria-label="选择要同步商品的账号"
|
||||
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
|
||||
value={selectedAccount}
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
>
|
||||
<option value="">请选择账号</option>
|
||||
{accounts.map(acc => (
|
||||
<option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleSync}
|
||||
disabled={loading || !selectedAccount}
|
||||
@@ -569,7 +618,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
|
||||
{items.map(item => {
|
||||
{visibleItems.map(item => {
|
||||
const linkedRules = rulesForItem(item);
|
||||
const hasRule = linkedRules.length > 0;
|
||||
return (
|
||||
@@ -603,6 +652,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4">{item.item_title}</h3>
|
||||
<div className="mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700" title={accountNickname(item.cookie_id)}>
|
||||
<User className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate whitespace-nowrap">{accountNickname(item.cookie_id)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center text-[10px] text-gray-500 mb-2">
|
||||
<span className="bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]">ID: {item.item_id}</span>
|
||||
<span className={`inline-flex items-center gap-1 font-bold ${hasRule ? 'text-emerald-600' : 'text-amber-600'}`}>
|
||||
@@ -622,10 +675,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{items.length === 0 && (
|
||||
{visibleItems.length === 0 && (
|
||||
<div className="col-span-full py-20 text-center text-gray-400">
|
||||
<ShoppingBag className="w-12 h-12 mx-auto mb-4 opacity-30" />
|
||||
暂无商品数据,请选择账号进行同步
|
||||
{accountFilter ? '该账号暂无商品数据' : '暂无商品数据,请选择账号进行同步'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -675,7 +728,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<label className="block text-sm font-bold text-gray-700">所属账号</label>
|
||||
<select className="w-full ios-input px-4 py-3 rounded-xl" value={addForm.cookie_id} onChange={e => setAddForm({...addForm, cookie_id: e.target.value})}>
|
||||
<option value="">选择账号</option>
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
@@ -727,7 +780,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<label className="block text-sm font-bold text-gray-700">发布账号</label>
|
||||
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.cookie_id} onChange={e => setPublishForm({...publishForm, cookie_id: e.target.value})}>
|
||||
<option value="">选择账号</option>
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
@@ -857,7 +910,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
>
|
||||
<option value="">选择账号</option>
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
|
||||
</select>
|
||||
<p className="text-xs text-gray-500">表格中“账号ID”为空时,会使用这里选择的账号。</p>
|
||||
</div>
|
||||
@@ -924,7 +977,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-50 text-gray-700">
|
||||
{[
|
||||
['账号ID', '没有在上方选择默认账号时填写', '填写账号 ID;已经选择默认账号时可以留空'],
|
||||
['账号ID', '需要覆盖默认账号时填写', '上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行'],
|
||||
['标题', '每个商品都要填', '填写买家能看到的商品标题'],
|
||||
['描述', '可以留空', '留空时会使用商品标题作为描述'],
|
||||
['价格', '每个商品都要填', '只填数字,例如 19.90'],
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
Check, MessageCircle, Mail, Webhook, Send as Telegram, Eye, EyeOff, Save,
|
||||
} from 'lucide-react';
|
||||
import { normalizeSMTPSettings } from '../smtpSettings';
|
||||
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../notificationEmailConfig';
|
||||
|
||||
type ChannelTypeMeta = {
|
||||
label: string;
|
||||
@@ -139,18 +140,14 @@ const CHANNEL_TYPES: Record<NotificationChannelType, ChannelTypeMeta> = {
|
||||
icon: Mail,
|
||||
fields: [
|
||||
{ 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: [
|
||||
'先在页面上方保存系统级 SMTP 服务器、端口、发件邮箱和授权码',
|
||||
'邮件渠道只需要填写收件邮箱',
|
||||
'如果某个渠道要使用不同发件邮箱,再填写下面的覆盖 SMTP 字段',
|
||||
'通常先保存页面中的系统 SMTP 配置',
|
||||
'邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP',
|
||||
'只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置',
|
||||
],
|
||||
note: '收件邮箱会写入 to_email;SMTP 字段留空时后端会复用系统级 SMTP 配置。',
|
||||
note: '继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。',
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -188,6 +185,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
const [smtp, setSmtp] = useState<SystemSettings>({});
|
||||
const [smtpSaving, setSmtpSaving] = useState(false);
|
||||
const [showSmtpPassword, setShowSmtpPassword] = useState(false);
|
||||
const [showChannelSmtpPassword, setShowChannelSmtpPassword] = useState(false);
|
||||
|
||||
const [form, setForm] = useState({
|
||||
name: '',
|
||||
@@ -256,18 +254,28 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] });
|
||||
setShowChannelSmtpPassword(false);
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
const openEdit = (ch: NotificationChannel) => {
|
||||
setEditing(ch);
|
||||
const normalizedEmailConfig = ch.type === 'email'
|
||||
? normalizeEmailChannelConfig({ ...(ch.config || {}) })
|
||||
: null;
|
||||
const config = normalizedEmailConfig
|
||||
? (normalizedEmailConfig.use_custom_smtp === true
|
||||
? enableCustomSMTP(normalizedEmailConfig, smtp)
|
||||
: normalizedEmailConfig)
|
||||
: { ...(ch.config || {}) };
|
||||
setForm({
|
||||
name: ch.name,
|
||||
type: ch.type,
|
||||
enabled: ch.enabled,
|
||||
config: { ...(ch.config || {}) },
|
||||
config,
|
||||
event_types: ch.event_types || [],
|
||||
});
|
||||
setShowChannelSmtpPassword(false);
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
@@ -283,9 +291,27 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
showToast('error', '请填写渠道名称');
|
||||
return;
|
||||
}
|
||||
let config = form.config;
|
||||
if (form.type === 'email') {
|
||||
config = buildEmailChannelConfig(form.config);
|
||||
if (config.use_custom_smtp) {
|
||||
const required = [
|
||||
['smtp_server', '独立 SMTP 服务器'],
|
||||
['smtp_port', '独立 SMTP 端口'],
|
||||
['smtp_user', '独立 SMTP 登录邮箱'],
|
||||
['smtp_password', '独立 SMTP 密码 / 授权码'],
|
||||
['smtp_from_address', '独立 SMTP 发件地址'],
|
||||
] as const;
|
||||
const missing = required.find(([key]) => !String(config[key] || '').trim());
|
||||
if (missing) {
|
||||
showToast('error', `请填写 ${missing[1]}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = { name: form.name.trim(), type: form.type, config: form.config, event_types: form.event_types, enabled: form.enabled };
|
||||
const payload = { name: form.name.trim(), type: form.type, config, event_types: form.event_types, enabled: form.enabled };
|
||||
if (editing) {
|
||||
await updateNotificationChannel(editing.id, payload);
|
||||
} else {
|
||||
@@ -664,6 +690,137 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{form.type === 'email' && (
|
||||
<div className="overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40">
|
||||
<div className="flex items-center justify-between gap-4 p-4">
|
||||
<div>
|
||||
<div className="text-sm font-extrabold text-gray-900">SMTP 来源</div>
|
||||
<p className="mt-1 text-xs leading-5 text-gray-500">
|
||||
{form.config.use_custom_smtp === true
|
||||
? '当前渠道使用一套完整、独立的发件配置。'
|
||||
: '当前渠道完整继承系统 SMTP,只单独设置收件邮箱。'}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const useCustom = form.config.use_custom_smtp === true;
|
||||
setForm({
|
||||
...form,
|
||||
config: useCustom
|
||||
? { ...form.config, use_custom_smtp: false }
|
||||
: enableCustomSMTP(form.config, smtp),
|
||||
});
|
||||
}}
|
||||
className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
|
||||
aria-label="使用独立 SMTP"
|
||||
>
|
||||
<span className={`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${form.config.use_custom_smtp === true ? 'translate-x-5' : ''}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{form.config.use_custom_smtp === true && (
|
||||
<div className="space-y-4 border-t border-blue-100 bg-white/80 p-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">SMTP 服务器 <span className="text-red-500">*</span></label>
|
||||
<input
|
||||
type="text"
|
||||
value={String(form.config.smtp_server || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_server: e.target.value } })}
|
||||
placeholder="smtp.qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">SMTP 端口 <span className="text-red-500">*</span></label>
|
||||
<input
|
||||
type="number"
|
||||
value={String(form.config.smtp_port || 587)}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_port: e.target.value } })}
|
||||
placeholder="587"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">登录邮箱 <span className="text-red-500">*</span></label>
|
||||
<input
|
||||
type="email"
|
||||
value={String(form.config.smtp_user || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_user: e.target.value } })}
|
||||
placeholder="your-email@qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">密码 / 授权码 <span className="text-red-500">*</span></label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showChannelSmtpPassword ? 'text' : 'password'}
|
||||
value={String(form.config.smtp_password || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_password: e.target.value } })}
|
||||
placeholder="输入密码或授权码"
|
||||
className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowChannelSmtpPassword(value => !value)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600"
|
||||
>
|
||||
{showChannelSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={String(form.config.smtp_from_name || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_from_name: e.target.value } })}
|
||||
placeholder="闲鱼自动回复系统"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">发件邮箱地址 <span className="text-red-500">*</span></label>
|
||||
<input
|
||||
type="email"
|
||||
value={String(form.config.smtp_from_address || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_from_address: e.target.value } })}
|
||||
placeholder="your-email@qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.config.smtp_use_tls !== false}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_use_tls: e.target.checked, smtp_use_ssl: e.target.checked ? false : form.config.smtp_use_ssl } })}
|
||||
/>
|
||||
STARTTLS(常用于 587)
|
||||
</label>
|
||||
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.config.smtp_use_ssl === true}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_use_ssl: e.target.checked, smtp_use_tls: e.target.checked ? false : form.config.smtp_use_tls } })}
|
||||
/>
|
||||
SSL/TLS 直连(常用于 465)
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-800">通知内容</label>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Order, OrderStatus, Item } from '../types';
|
||||
import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems } from '../services/api';
|
||||
import { AccountDetail, Order, OrderStatus, Item } from '../types';
|
||||
import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems, getAccountDetails } from '../services/api';
|
||||
import { Search, MoreHorizontal, Truck, RefreshCw, Copy, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, Phone, MapPin, Upload, ExternalLink, Trash2 } from 'lucide-react';
|
||||
import { failedOrderImportRows, normalizeOrderImportResult, OrderImportResult } from './orderImportState';
|
||||
import { formatLocalDateTime } from '../dateTime';
|
||||
|
||||
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
const styles = {
|
||||
@@ -36,8 +37,10 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
const OrderList: React.FC = () => {
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||
const [itemNames, setItemNames] = useState<Record<string, string>>({});
|
||||
const [filter, setFilter] = useState('all');
|
||||
const [accountFilter, setAccountFilter] = useState('');
|
||||
const [searchText, setSearchText] = useState(''); // 搜索文本
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const requestSequence = useRef(0);
|
||||
@@ -65,7 +68,7 @@ const OrderList: React.FC = () => {
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await getOrders(undefined, filter, page, 20, debouncedSearch);
|
||||
const res = await getOrders(accountFilter || undefined, filter, page, 20, debouncedSearch);
|
||||
if (sequence !== requestSequence.current) return;
|
||||
setOrders(res.data);
|
||||
setTotalPages(res.total_pages);
|
||||
@@ -77,15 +80,15 @@ const OrderList: React.FC = () => {
|
||||
};
|
||||
|
||||
// 从订单的 item_id 查找对应的商品名称(通过标题匹配)
|
||||
const getItemNameById = (orderId: string, orderItemTitle?: string): string => {
|
||||
const getItemNameById = (cookieId: string, orderId: string, orderItemTitle?: string): string => {
|
||||
// 如果订单有 item_title,优先使用
|
||||
if (orderItemTitle && orderItemTitle.trim()) {
|
||||
return orderItemTitle;
|
||||
}
|
||||
|
||||
// 尝试通过 item_id 直接匹配
|
||||
if (itemNames[orderId]) {
|
||||
return itemNames[orderId];
|
||||
if (itemNames[`${cookieId}:${orderId}`]) {
|
||||
return itemNames[`${cookieId}:${orderId}`];
|
||||
}
|
||||
|
||||
// 尝试在商品列表中查找相似标题的商品
|
||||
@@ -113,7 +116,7 @@ const OrderList: React.FC = () => {
|
||||
items.forEach(item => {
|
||||
// 使用 item_id 作为键,商品标题作为值
|
||||
if (item.item_id) {
|
||||
namesMap[item.item_id] = item.item_title || item.item_id;
|
||||
namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
|
||||
}
|
||||
});
|
||||
setItemNames(namesMap);
|
||||
@@ -123,7 +126,7 @@ const OrderList: React.FC = () => {
|
||||
const namesMap: Record<string, string> = {};
|
||||
itemsList.forEach(item => {
|
||||
if (item.item_id) {
|
||||
namesMap[item.item_id] = item.item_title || item.item_id;
|
||||
namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
|
||||
}
|
||||
});
|
||||
setItemNames(namesMap);
|
||||
@@ -139,10 +142,11 @@ const OrderList: React.FC = () => {
|
||||
|
||||
useEffect(() => {
|
||||
loadOrders();
|
||||
}, [filter, page, debouncedSearch]);
|
||||
}, [accountFilter, filter, page, debouncedSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
getItems().then((itemsList) => {
|
||||
Promise.all([getAccountDetails(), getItems()]).then(([accountList, itemsList]) => {
|
||||
setAccounts(accountList);
|
||||
setItems(itemsList);
|
||||
buildItemNamesMapFrom(itemsList);
|
||||
}).catch((e) => {
|
||||
@@ -150,10 +154,25 @@ const OrderList: React.FC = () => {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const accountMap = useMemo(
|
||||
() => new Map(accounts.map(account => [account.id, account])),
|
||||
[accounts],
|
||||
);
|
||||
|
||||
const accountName = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
const name = account?.remark || account?.nickname;
|
||||
return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
|
||||
};
|
||||
const accountNickname = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
return account?.remark || account?.nickname || '未命名账号';
|
||||
};
|
||||
|
||||
const handleSync = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await syncOrders();
|
||||
const result = await syncOrders(accountFilter || undefined, filter);
|
||||
await loadOrders();
|
||||
if (result?.message) {
|
||||
alert(result.message);
|
||||
@@ -357,7 +376,22 @@ const OrderList: React.FC = () => {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="relative w-full md:w-auto group">
|
||||
<div className="flex w-full md:w-auto flex-col sm:flex-row gap-3">
|
||||
<div className="relative">
|
||||
<UserIcon className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<select
|
||||
aria-label="按账号筛选订单"
|
||||
value={accountFilter}
|
||||
onChange={(event) => { setAccountFilter(event.target.value); setPage(1); }}
|
||||
className="ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="relative group">
|
||||
<Search className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors" />
|
||||
<input
|
||||
type="text"
|
||||
@@ -366,6 +400,7 @@ const OrderList: React.FC = () => {
|
||||
onChange={(e) => { setSearchText(e.target.value); setPage(1); }}
|
||||
className="ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -395,10 +430,14 @@ const OrderList: React.FC = () => {
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="font-bold text-gray-900 line-clamp-1 text-sm">
|
||||
{getItemNameById(order.item_id, order.item_title)}
|
||||
{getItemNameById(order.cookie_id, order.item_id, order.item_title)}
|
||||
</div>
|
||||
<div className="mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700" title={accountNickname(order.cookie_id)}>
|
||||
<UserIcon className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate whitespace-nowrap">{accountNickname(order.cookie_id)}</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 mt-1 font-medium">订单ID: {order.order_id}</div>
|
||||
<div className="text-xs text-gray-400 mt-0.5">数量: {order.quantity} • {order.created_at}</div>
|
||||
<div className="text-xs text-gray-400 mt-0.5">数量: {order.quantity} • {formatLocalDateTime(order.created_at)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
@@ -536,6 +575,10 @@ const OrderList: React.FC = () => {
|
||||
<div className="text-xs text-gray-500 mb-1">订单号</div>
|
||||
<div className="font-mono text-sm font-bold text-gray-900">{selectedOrder.order_id}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500 mb-1">所属账号</div>
|
||||
<div className="truncate whitespace-nowrap text-sm font-bold text-blue-700" title={accountNickname(selectedOrder.cookie_id)}>{accountNickname(selectedOrder.cookie_id)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500 mb-1">状态</div>
|
||||
<StatusBadge status={selectedOrder.status} />
|
||||
@@ -550,7 +593,7 @@ const OrderList: React.FC = () => {
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<div className="text-xs text-gray-500 mb-1">创建时间</div>
|
||||
<div className="text-sm font-medium text-gray-700">{selectedOrder.created_at}</div>
|
||||
<div className="text-sm font-medium text-gray-700">{formatLocalDateTime(selectedOrder.created_at)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -564,7 +607,7 @@ const OrderList: React.FC = () => {
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<div className="font-bold text-gray-900 mb-1">
|
||||
{getItemNameById(selectedOrder.item_id, selectedOrder.item_title)}
|
||||
{getItemNameById(selectedOrder.cookie_id, selectedOrder.item_id, selectedOrder.item_title)}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500">商品ID: {selectedOrder.item_id}</div>
|
||||
{selectedOrder.item_price && (
|
||||
|
||||
@@ -1280,7 +1280,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="86400"
|
||||
max="3600"
|
||||
value={variant.delay_seconds || 0}
|
||||
onChange={event => updateVariant(index, { delay_seconds: Math.max(0, Number(event.target.value) || 0) })}
|
||||
className="w-28 ios-input px-2 py-1.5 rounded-lg text-xs"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React from 'react';
|
||||
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap, Bell } from 'lucide-react';
|
||||
import { YdisksBrandIcon } from './YdisksLogo';
|
||||
|
||||
interface SidebarProps {
|
||||
activeTab: string;
|
||||
@@ -24,8 +25,8 @@ const Sidebar: React.FC<SidebarProps> = ({ activeTab, isAdmin = false, onNavigat
|
||||
<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)]">
|
||||
<div className="p-6">
|
||||
<div className="flex items-center gap-3 mb-12 px-2">
|
||||
<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))' }}>
|
||||
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full" />
|
||||
<div className="shrink-0">
|
||||
<YdisksBrandIcon sizeClass="w-10 h-10" />
|
||||
</div>
|
||||
<h1 className="text-xl font-extrabold tracking-tight text-gray-900">Ydisks闲鱼助手 <span className="text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1">PRO</span></h1>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import YdisksLogo, { YdisksBrandIcon } from './YdisksLogo';
|
||||
|
||||
describe('YdisksLogo', () => {
|
||||
test('uses the complete 256px brand coordinate system', () => {
|
||||
const html = renderToStaticMarkup(<YdisksLogo />);
|
||||
expect(html).toContain('viewBox="0 0 256 256"');
|
||||
expect(html).toContain('M121.73,57.0003');
|
||||
expect(html).toContain('fill="currentColor"');
|
||||
});
|
||||
|
||||
test('renders the complete gradient squircle brand wrapper', () => {
|
||||
const html = renderToStaticMarkup(<YdisksBrandIcon />);
|
||||
expect(html).toContain('viewBox="0 0 120 120"');
|
||||
expect(html).toContain('id="login-squircle-gradient"');
|
||||
expect(html).toContain('M 114.00 60.00');
|
||||
expect(html).toContain('w-12 h-12');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import React from 'react';
|
||||
|
||||
interface YdisksLogoProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface YdisksBrandIconProps {
|
||||
sizeClass?: string;
|
||||
logoClassName?: string;
|
||||
}
|
||||
|
||||
const YdisksLogo: React.FC<YdisksLogoProps> = ({ className = 'w-full h-full text-white' }) => (
|
||||
<svg className={className} viewBox="0 0 256 256" aria-hidden="true">
|
||||
<g stroke="none" fill="none" fillRule="evenodd">
|
||||
<path d="M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z" fill="currentColor" />
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const YdisksBrandIcon: React.FC<YdisksBrandIconProps> = ({
|
||||
sizeClass = 'w-12 h-12',
|
||||
logoClassName = 'w-full h-full text-white',
|
||||
}) => (
|
||||
<div className="relative z-10 flex items-center justify-center">
|
||||
<div className="absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25" />
|
||||
<div className={`relative ${sizeClass} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`}>
|
||||
<svg className="absolute inset-0 w-full h-full" viewBox="0 0 120 120" aria-hidden="true">
|
||||
<defs>
|
||||
<linearGradient id="login-squircle-gradient" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stopColor="#0094f7" />
|
||||
<stop offset="100%" stopColor="#287efe" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d="M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z" fill="url(#login-squircle-gradient)" />
|
||||
</svg>
|
||||
<div className="relative z-10 flex items-center justify-center w-full h-full">
|
||||
<YdisksLogo className={logoClassName} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default YdisksLogo;
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import type { Card } from '../types';
|
||||
import { filterCards } from './cardListState';
|
||||
|
||||
const cards = [
|
||||
{ id: 1, name: '年终总结 PPT', type: 'text' },
|
||||
{ id: 2, name: '年终总结兑换码', type: 'data' },
|
||||
{ id: 3, name: '产品介绍 PPT', type: 'text' },
|
||||
] as Card[];
|
||||
|
||||
describe('filterCards', () => {
|
||||
test('combines type and name filters with AND semantics', () => {
|
||||
expect(filterCards(cards, 'text', '年终')).toEqual([cards[0]]);
|
||||
});
|
||||
|
||||
test('matches names case-insensitively and ignores surrounding whitespace', () => {
|
||||
expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Card } from '../types';
|
||||
|
||||
export const filterCards = (
|
||||
cards: Card[],
|
||||
typeFilter: Card['type'] | '',
|
||||
nameSearch: string,
|
||||
): Card[] => {
|
||||
const keyword = nameSearch.trim().toLocaleLowerCase();
|
||||
return cards.filter(card => (
|
||||
(!typeFilter || card.type === typeFilter)
|
||||
&& (!keyword || card.name.toLocaleLowerCase().includes(keyword))
|
||||
));
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { formatLocalDateTime } from './dateTime';
|
||||
|
||||
describe('formatLocalDateTime', () => {
|
||||
test('uses the browser local timezone and the standard second-level format', () => {
|
||||
expect(formatLocalDateTime(new Date(2026, 6, 15, 10, 54, 12))).toBe('2026-07-15 10:54:12');
|
||||
});
|
||||
|
||||
test('returns a placeholder for missing or invalid timestamps', () => {
|
||||
expect(formatLocalDateTime()).toBe('-');
|
||||
expect(formatLocalDateTime('not-a-date')).toBe('-');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
const padTwoDigits = (value: number): string => String(value).padStart(2, '0');
|
||||
|
||||
/** Format a timestamp in the browser's current timezone. */
|
||||
export const formatLocalDateTime = (value?: string | number | Date | null): string => {
|
||||
if (value === undefined || value === null || value === '') return '-';
|
||||
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '-';
|
||||
|
||||
return [
|
||||
date.getFullYear(),
|
||||
padTwoDigits(date.getMonth() + 1),
|
||||
padTwoDigits(date.getDate()),
|
||||
].join('-') + ' ' + [
|
||||
padTwoDigits(date.getHours()),
|
||||
padTwoDigits(date.getMinutes()),
|
||||
padTwoDigits(date.getSeconds()),
|
||||
].join(':');
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from './notificationEmailConfig';
|
||||
|
||||
describe('email notification SMTP modes', () => {
|
||||
test('recognizes legacy channel overrides as custom SMTP', () => {
|
||||
expect(normalizeEmailChannelConfig({ to_email: 'to@example.com', smtp_server: 'legacy.example.com' }).use_custom_smtp).toBe(true);
|
||||
});
|
||||
|
||||
test('inherit mode removes every channel-level SMTP override', () => {
|
||||
expect(buildEmailChannelConfig({
|
||||
to_email: ' to@example.com ',
|
||||
use_custom_smtp: false,
|
||||
smtp_server: 'stale.example.com',
|
||||
smtp_use_tls: false,
|
||||
})).toEqual({ to_email: 'to@example.com', use_custom_smtp: false });
|
||||
});
|
||||
|
||||
test('custom mode starts from a complete copy of system SMTP settings', () => {
|
||||
const result = enableCustomSMTP({ to_email: 'to@example.com' }, {
|
||||
smtp_server: 'smtp.example.com',
|
||||
smtp_port: 465,
|
||||
smtp_user: 'from@example.com',
|
||||
smtp_password: 'secret',
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
use_custom_smtp: true,
|
||||
smtp_server: 'smtp.example.com',
|
||||
smtp_port: 465,
|
||||
smtp_from_address: 'from@example.com',
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
const smtpOverrideKeys = [
|
||||
'smtp_server',
|
||||
'smtp_port',
|
||||
'smtp_user',
|
||||
'smtp_password',
|
||||
'smtp_from_name',
|
||||
'smtp_from_address',
|
||||
'smtp_use_tls',
|
||||
'smtp_use_ssl',
|
||||
] as const;
|
||||
|
||||
const parseBoolean = (value: unknown, fallback: boolean): boolean => {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'string') {
|
||||
if (['true', '1', 'yes', 'on'].includes(value.toLowerCase())) return true;
|
||||
if (['false', '0', 'no', 'off'].includes(value.toLowerCase())) return false;
|
||||
}
|
||||
return fallback;
|
||||
};
|
||||
|
||||
export const normalizeEmailChannelConfig = (config: Record<string, unknown>): Record<string, unknown> => {
|
||||
const hasExplicitMode = Object.prototype.hasOwnProperty.call(config, 'use_custom_smtp');
|
||||
const hasLegacyOverrides = smtpOverrideKeys.some(key => String(config[key] ?? '').trim() !== '');
|
||||
return {
|
||||
...config,
|
||||
use_custom_smtp: hasExplicitMode
|
||||
? parseBoolean(config.use_custom_smtp, false)
|
||||
: hasLegacyOverrides,
|
||||
};
|
||||
};
|
||||
|
||||
export const enableCustomSMTP = (
|
||||
config: Record<string, unknown>,
|
||||
systemSettings: Record<string, unknown>,
|
||||
): Record<string, unknown> => {
|
||||
const next: Record<string, unknown> = { ...config, use_custom_smtp: true };
|
||||
for (const key of smtpOverrideKeys) {
|
||||
if (String(next[key] ?? '').trim() === '' && systemSettings[key] !== undefined) {
|
||||
next[key] = systemSettings[key];
|
||||
}
|
||||
}
|
||||
next.smtp_port ||= 587;
|
||||
next.smtp_from_address ||= next.smtp_user || '';
|
||||
next.smtp_use_tls = parseBoolean(next.smtp_use_tls, true);
|
||||
next.smtp_use_ssl = parseBoolean(next.smtp_use_ssl, false);
|
||||
return next;
|
||||
};
|
||||
|
||||
export const buildEmailChannelConfig = (config: Record<string, unknown>): Record<string, unknown> => {
|
||||
const normalized = normalizeEmailChannelConfig(config);
|
||||
const result: Record<string, unknown> = {
|
||||
to_email: String(normalized.to_email ?? '').trim(),
|
||||
use_custom_smtp: normalized.use_custom_smtp === true,
|
||||
};
|
||||
if (result.use_custom_smtp) {
|
||||
for (const key of smtpOverrideKeys) result[key] = normalized[key];
|
||||
}
|
||||
return result;
|
||||
};
|
||||
@@ -71,13 +71,14 @@ describe('frontend navigation routing', () => {
|
||||
expect(settings).toContain('只有网络不可用或超时才回退本机引擎');
|
||||
});
|
||||
|
||||
test('email notification config uses backend recipient field names', () => {
|
||||
test('email notification config separates system and custom SMTP modes', () => {
|
||||
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).toContain('完整继承系统 SMTP');
|
||||
expect(notifications).toContain('use_custom_smtp');
|
||||
expect(notifications).not.toContain("key: 'from'");
|
||||
expect(notifications).not.toContain('注册验证码');
|
||||
});
|
||||
|
||||
@@ -187,6 +187,18 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('getItems forwards the selected account filter', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([]));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await getItems('account-2');
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/items?cookie_id=account-2', expect.objectContaining({
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
|
||||
test('getSystemSettings normalizes numeric renewal retention', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
ai_model: 'qwen-plus',
|
||||
|
||||
@@ -159,6 +159,19 @@ export const updateAccountSettings = async (id: string, data: AccountSettingsUpd
|
||||
return put(`/cookies/${id}/settings`, data);
|
||||
};
|
||||
|
||||
export interface LongLoginSettings {
|
||||
can_open_long_login: boolean;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export const getLongLoginSettings = async (id: string): Promise<LongLoginSettings> => {
|
||||
return get(`/cookies/${id}/long-login`);
|
||||
};
|
||||
|
||||
export const setLongLoginSettings = async (id: string, enabled: boolean): Promise<LongLoginSettings> => {
|
||||
return put(`/cookies/${id}/long-login`, { enabled });
|
||||
};
|
||||
|
||||
export interface PasswordLoginStartResponse {
|
||||
success: boolean;
|
||||
session_id?: string;
|
||||
@@ -413,8 +426,8 @@ export const appendCardData = async (cardId: string | number, content: string):
|
||||
const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
value === true || value === 1 || value === '1';
|
||||
|
||||
export const getItems = async (): Promise<Item[]> => {
|
||||
const res = await get<any>('/items');
|
||||
export const getItems = async (cookieId?: string): Promise<Item[]> => {
|
||||
const res = await get<any>('/items', cookieId ? { cookie_id: cookieId } : undefined);
|
||||
const items = Array.isArray(res) ? res : (res.items || []);
|
||||
return items.map((item: any) => ({
|
||||
...item,
|
||||
|
||||
@@ -3,6 +3,7 @@ package account
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -12,8 +13,34 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/ws"
|
||||
)
|
||||
|
||||
type fakeWSDialer struct{}
|
||||
|
||||
func (fakeWSDialer) Dial(context.Context, ws.Config, *slog.Logger) (engine.WSConn, error) {
|
||||
return fakeWSConn{}, nil
|
||||
}
|
||||
|
||||
type fakeWSConn struct{}
|
||||
|
||||
func (fakeWSConn) Register(context.Context, string, string) error { return nil }
|
||||
func (fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
func (fakeWSConn) ReceiveLoop(ctx context.Context, _ func(map[string]any)) error {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
func (fakeWSConn) Close() error { return nil }
|
||||
func (fakeWSConn) SendText(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
func (fakeWSConn) SendImage(context.Context, string, string, string, string, int, int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// fakeMtop 是注入 engine.Account 的可控 mtop 客户端,避免真实网络。
|
||||
// refreshErr 非空时 RefreshToken 返回该错误;block 非空时阻塞到该 chan
|
||||
// 关闭或 ctx 取消(用于让 Run 挂起、模拟"账号在线运行中")。
|
||||
@@ -98,6 +125,7 @@ func startAccountWithMtop(t *testing.T, mgr *Manager, cookieID, cookieValue stri
|
||||
Handler: mgr.handler,
|
||||
Logger: mgr.logger,
|
||||
MTop: mtopClient,
|
||||
WSDialer: fakeWSDialer{},
|
||||
})
|
||||
accCtx, accCancel := context.WithCancel(runCtx)
|
||||
ma := &managedAccount{
|
||||
|
||||
@@ -112,7 +112,7 @@ func verifiedRenewService(t *testing.T) (xrenew.Service, func()) {
|
||||
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
|
||||
case "/silentHasLogin.do":
|
||||
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"})
|
||||
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
case "/setLoginSettings.do":
|
||||
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"})
|
||||
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -175,13 +176,31 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(60000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("COOKIES续期访问首页异常", "cookieID", cookieID, "err", err)
|
||||
navigate := func() error {
|
||||
_, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(60000),
|
||||
})
|
||||
return err
|
||||
}
|
||||
if expectsOfficialSilentLogin(cookieStr) {
|
||||
response, err := page.ExpectResponse("**/newlogin/silentHasLogin.do**", navigate, playwright.PageExpectResponseOptions{Timeout: playwright.Float(7000)})
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("等待官网静默续期请求完成: %w", err)
|
||||
}
|
||||
if response == nil || response.Status() < 200 || response.Status() >= 300 {
|
||||
return "", nil, fmt.Errorf("官网静默续期 HTTP 状态异常")
|
||||
}
|
||||
// 插件在业务成功后立即 location.reload;等待短暂调度窗口,再等待
|
||||
// 新文档进入 DOMContentLoaded,避免提取续期前 Cookie。
|
||||
page.WaitForTimeout(500)
|
||||
_ = page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{
|
||||
State: playwright.LoadStateDomcontentloaded,
|
||||
Timeout: playwright.Float(5000),
|
||||
})
|
||||
} else if err := navigate(); err != nil {
|
||||
m.logger.Warn("COOKIES续期访问消息页异常", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
time.Sleep(quickRenewPageLoadWait)
|
||||
if err := verifyHomeLoginState(page); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -199,6 +218,27 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
|
||||
return newCookies, newSnapshot, nil
|
||||
}
|
||||
|
||||
func expectsOfficialSilentLogin(cookieStr string) bool {
|
||||
cookies := cookierefresh.ParseCookieString(cookieStr)
|
||||
now := time.Now().UnixMilli()
|
||||
if futureCookieMillis(cookies["sdkSilent"], now) {
|
||||
return false
|
||||
}
|
||||
return futureCookieMillis(cookies["havana_lgc_exp"], now) || futureCookieMillis(cookies["cookie3_bak_exp"], now)
|
||||
}
|
||||
|
||||
func futureCookieMillis(raw string, now int64) bool {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return false
|
||||
}
|
||||
value, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
return value > now
|
||||
}
|
||||
|
||||
// CookieRenewSnapshot 兼容旧调用,等价于定时 COOKIES 快照续期。
|
||||
func (m *Manager) CookieRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
return m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
|
||||
|
||||
@@ -7,11 +7,9 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// AccountToken 持久化的账号登录凭证缓存(device_id + accessToken)。
|
||||
//
|
||||
// 设计动机(参考 xianyu-auto-reply 的 xy_token_cache):
|
||||
// - device_id 跨进程重启复用,避免每次重启换新设备 ID 触发阿里端设备绑定/风控;
|
||||
// - accessToken 缓存后,短重启可复用、瞬时 mtop 失败可回退到上次有效 token,不掉线。
|
||||
// AccountToken 持久化最近一次页面运行实例的 device_id 和 token 请求元数据。
|
||||
// accessToken 不用于后续 WebSocket 注册;官方消息页在每次 loginV2/reConnect
|
||||
// 前都会重新获取 token,页面重载后也会生成新的 device_id。
|
||||
type AccountToken struct {
|
||||
CookieID string
|
||||
DeviceID string
|
||||
@@ -56,17 +54,9 @@ func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToke
|
||||
return t.SaveBound(ctx, cookieID, deviceID, accessToken, expireAt, "")
|
||||
}
|
||||
|
||||
// SaveBound persists an access token together with the canonical Cookie state
|
||||
// from which it was issued. The binding lets a later reconnect reject a stale
|
||||
// token after an independent Cookie renewal without rotating device_id.
|
||||
// SaveBound persists an access token together with the page-runtime device ID
|
||||
// and canonical Cookie state from which it was issued.
|
||||
func (t *AccountTokens) SaveBound(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64, cookieFingerprint string) error {
|
||||
// device_id is an account identity, not part of the expiring token cache.
|
||||
// Once stored, token refreshes must never replace it.
|
||||
if existing, err := t.Get(ctx, cookieID); err == nil && existing.DeviceID != "" {
|
||||
deviceID = existing.DeviceID
|
||||
} else if err != nil && !errors.Is(err, ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
encryptedDeviceID, err := t.codec.encrypt("device-id", cookieID, deviceID)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -39,21 +39,21 @@ func TestAccountTokens_CRUD(t *testing.T) {
|
||||
t.Fatalf("Get 返回不匹配: %+v", tk)
|
||||
}
|
||||
|
||||
// 再次 Save 更新 token,但永久 device ID 不允许覆盖。
|
||||
// 页面运行实例变化后,再次 Save 同步更新 device ID 和 token。
|
||||
if err := store.Tokens.SaveBound(ctx, "cid", "dev-2", "tok-2", expire+1, "cookie-hash-2"); err != nil {
|
||||
t.Fatalf("Save upsert: %v", err)
|
||||
}
|
||||
tk, _ = store.Tokens.Get(ctx, "cid")
|
||||
if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 || tk.CookieFingerprint != "cookie-hash-2" {
|
||||
if tk.DeviceID != "dev-2" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 || tk.CookieFingerprint != "cookie-hash-2" {
|
||||
t.Fatalf("upsert 后字段应更新: %+v", tk)
|
||||
}
|
||||
|
||||
// Clear 只清 token,永久 device ID 必须保留。
|
||||
// Clear 只清 token,保留最近一次页面运行实例的 device ID。
|
||||
if err := store.Tokens.Clear(ctx, "cid"); err != nil {
|
||||
t.Fatalf("Clear: %v", err)
|
||||
}
|
||||
tk, err = store.Tokens.Get(ctx, "cid")
|
||||
if err != nil || tk.DeviceID != "dev-1" || tk.AccessToken != "" || tk.ExpireAt != 0 || tk.CookieFingerprint != "" {
|
||||
if err != nil || tk.DeviceID != "dev-2" || tk.AccessToken != "" || tk.ExpireAt != 0 || tk.CookieFingerprint != "" {
|
||||
t.Fatalf("Clear 后 device ID 应保留且 token 清空: tk=%+v err=%v", tk, err)
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ func TestAccountTokens_CRUD(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTokens_DeviceIDSurvivesTokenLifecycle(t *testing.T) {
|
||||
func TestAccountTokens_SaveTracksLatestRuntimeDeviceID(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
@@ -83,8 +83,8 @@ func TestAccountTokens_DeviceIDSurvivesTokenLifecycle(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
afterRestart, err := store.Tokens.GetOrCreateDeviceID(ctx, "cid", "device-after-restart")
|
||||
if err != nil || first != "device-first" || afterRestart != first {
|
||||
t.Fatalf("device ID changed across token lifecycle: first=%q after=%q err=%v", first, afterRestart, err)
|
||||
if err != nil || first != "device-first" || afterRestart != "device-replacement" {
|
||||
t.Fatalf("未保留最近一次运行时 device ID: first=%q after=%q err=%v", first, afterRestart, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -201,6 +201,9 @@ func orderUpsertAssignments(opts OrderUpsertOpts) ([]string, []any) {
|
||||
if opts.SystemShipped != nil {
|
||||
add("system_shipped", boolToInt(*opts.SystemShipped), true)
|
||||
}
|
||||
if opts.IsBargain != nil {
|
||||
add("is_bargain", boolToInt(*opts.IsBargain), true)
|
||||
}
|
||||
add("chat_id", opts.ChatID, opts.ChatID != "")
|
||||
add("item_id", opts.ItemID, opts.ItemID != "")
|
||||
add("buyer_id", opts.BuyerID, opts.BuyerID != "")
|
||||
@@ -277,6 +280,7 @@ type OrderUpsertOpts struct {
|
||||
ReceiverAddr string
|
||||
ReceiverCity string
|
||||
ChatID string
|
||||
IsBargain *bool
|
||||
SystemShipped *bool
|
||||
}
|
||||
|
||||
|
||||
+176
-137
@@ -18,6 +18,7 @@ import (
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
"xianyu-go/internal/xianyu/renew"
|
||||
@@ -87,7 +88,6 @@ type tokenCaptchaHandler interface {
|
||||
const (
|
||||
tokenRefreshStarted = "started"
|
||||
tokenRefreshSuccess = "success"
|
||||
tokenRefreshSuccessFromCache = "success_from_cache"
|
||||
tokenRefreshFailedCaptcha = "failed_captcha"
|
||||
tokenRefreshFailedCaptchaError = "failed_captcha_exception"
|
||||
tokenRefreshFailedTimeout = "failed_timeout"
|
||||
@@ -141,7 +141,7 @@ type Account struct {
|
||||
store *db.Store
|
||||
mtop mtop.Client
|
||||
renewer cookieRenewer
|
||||
wsDialer wsDialer
|
||||
wsDialer WSDialer
|
||||
handler Handler
|
||||
logger *slog.Logger
|
||||
|
||||
@@ -200,6 +200,7 @@ type debounceEntry struct {
|
||||
// WSConn 是 Account 对 ws 连接的最小契约。*ws.Conn 实现该接口;
|
||||
// 测试可注入 fakeWSConn 以隔离真实 WS 握手与网络。
|
||||
type WSConn interface {
|
||||
Register(ctx context.Context, deviceID, accessToken string) error
|
||||
HeartbeatLoop(ctx context.Context, interval time.Duration) error
|
||||
ReceiveLoop(ctx context.Context, onMessage func(map[string]any)) error
|
||||
Close() error
|
||||
@@ -207,15 +208,15 @@ type WSConn interface {
|
||||
SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error
|
||||
}
|
||||
|
||||
// wsDialer 抽象 ws.Dial,便于测试替身。
|
||||
type wsDialer interface {
|
||||
// WSDialer 抽象 WebSocket 打开阶段,便于测试隔离真实网络。
|
||||
type WSDialer interface {
|
||||
Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error)
|
||||
}
|
||||
|
||||
type defaultDialer struct{}
|
||||
|
||||
func (defaultDialer) Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error) {
|
||||
return ws.Dial(ctx, cfg, logger)
|
||||
return ws.Open(ctx, cfg, logger)
|
||||
}
|
||||
|
||||
type cookieRenewer interface {
|
||||
@@ -243,6 +244,8 @@ type Config struct {
|
||||
MTop mtop.Client
|
||||
// Renewer 可选:注入 Cookie 接口续期服务以便测试 mock。nil 时使用默认实现。
|
||||
Renewer cookieRenewer
|
||||
// WSDialer 可选:用于测试隔离原生 WebSocket 握手。
|
||||
WSDialer WSDialer
|
||||
}
|
||||
|
||||
// New 构造单账号运行时(未启动)。
|
||||
@@ -262,6 +265,10 @@ func New(cfg Config) *Account {
|
||||
}
|
||||
cookies := protocol.TransCookies(cfg.CookieStr)
|
||||
myid := cookies["unb"]
|
||||
wsDialer := cfg.WSDialer
|
||||
if wsDialer == nil {
|
||||
wsDialer = defaultDialer{}
|
||||
}
|
||||
a := &Account{
|
||||
CookieID: cfg.CookieID,
|
||||
CookieStr: cfg.CookieStr,
|
||||
@@ -269,7 +276,7 @@ func New(cfg Config) *Account {
|
||||
store: cfg.Store,
|
||||
mtop: mtopClient,
|
||||
renewer: renewer,
|
||||
wsDialer: defaultDialer{},
|
||||
wsDialer: wsDialer,
|
||||
handler: cfg.Handler,
|
||||
logger: logger.With("account", cfg.CookieID),
|
||||
deviceID: protocol.GenerateDeviceID(myid),
|
||||
@@ -281,14 +288,6 @@ func New(cfg Config) *Account {
|
||||
runtimeMessage: "正在启动账号服务",
|
||||
runtimeUpdatedAt: time.Now(),
|
||||
}
|
||||
if cfg.Store != nil && cfg.Store.Tokens != nil {
|
||||
deviceID, err := cfg.Store.Tokens.GetOrCreateDeviceID(context.Background(), cfg.CookieID, a.deviceID)
|
||||
if err != nil {
|
||||
logger.Error("读取或保存账号 device ID 失败", "account", cfg.CookieID, "err", err)
|
||||
} else {
|
||||
a.deviceID = deviceID
|
||||
}
|
||||
}
|
||||
if cfg.Store != nil {
|
||||
a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger)
|
||||
}
|
||||
@@ -308,6 +307,11 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.runtimeCtx = ctx
|
||||
a.accepting = true
|
||||
a.taskMu.Unlock()
|
||||
// 对应官网页面初始化时执行一次 auto-login plugin。成功更新 Cookie 时,
|
||||
// adoptRecoveredCookie 会旋转本次引擎身份,等价于页面 reload 后新建引擎。
|
||||
if a.renewer != nil {
|
||||
_ = a.tryAPIRenew(ctx)
|
||||
}
|
||||
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
@@ -322,8 +326,25 @@ func (a *Account) Run(parent context.Context) error {
|
||||
// 每次新建 IM 连接前吸收数据库中的最新 Cookie。健康连接不会被续期任务
|
||||
// 主动打断;Cookie 变化只会使本次重连放弃旧 token 并重新派生。
|
||||
a.reloadCookieFromDB(ctx)
|
||||
token, cookieStr, err := a.acquireRuntimeToken(ctx)
|
||||
|
||||
// 官网先完成原生 WebSocket 握手,再从 authTokenCallback 获取本次
|
||||
// 连接专用 token,最后发送 /reg。
|
||||
conn, err := a.wsDialer.Dial(ctx, ws.Config{Recorder: a.wsRecorder()}, a.logger)
|
||||
if err != nil {
|
||||
a.logger.Error("WS 握手失败", "err", err)
|
||||
if retryErr := a.handleWSConnectFailure(ctx, err, &invalidTokenRetried); retryErr != nil {
|
||||
return retryErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
connectedAt := time.Now()
|
||||
// The official web client calls
|
||||
// mtop.taobao.idlemessage.pc.login.token from authTokenCallback for every
|
||||
// loginV2/reConnect attempt. Do the same here: an access token belongs to
|
||||
// one connection attempt and must never be reused for a later /reg.
|
||||
token, cookieStr, err := a.acquireFreshConnectionToken(ctx)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
a.logger.Error("获取 token 失败", "err", err)
|
||||
a.mu.Lock()
|
||||
status := a.lastTokenStatus
|
||||
@@ -374,23 +395,7 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务")
|
||||
a.logger.Info("token 刷新成功")
|
||||
|
||||
// 2) 连接 WS + 注册。
|
||||
var recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
|
||||
if a.store != nil && a.store.WSMessages != nil {
|
||||
recorder = func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
|
||||
if err := a.store.WSMessages.Add(context.Background(), db.WSMessage{
|
||||
CookieID: a.CookieID,
|
||||
Direction: direction,
|
||||
RawText: rawText,
|
||||
ParsedJSON: parsedJSON,
|
||||
MessageKind: "",
|
||||
ParseStatus: parseStatus,
|
||||
Error: errMsg,
|
||||
}); err != nil {
|
||||
a.logger.Error("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 2) 使用刚获得的 token 注册已经打开的 WS。
|
||||
a.mu.Lock()
|
||||
deviceID := a.deviceID
|
||||
a.mu.Unlock()
|
||||
@@ -400,50 +405,17 @@ func (a *Account) Run(parent context.Context) error {
|
||||
}
|
||||
if !a.cookieSnapshotMatchesDB(ctx, cookieStr) {
|
||||
credentialUnlock()
|
||||
_ = conn.Close()
|
||||
a.reloadCookieFromDB(ctx)
|
||||
continue
|
||||
}
|
||||
attemptStartedAt := time.Now()
|
||||
conn, err := a.wsDialer.Dial(ctx, ws.Config{
|
||||
CookieStr: cookieStr,
|
||||
DeviceID: deviceID,
|
||||
AccessToken: token,
|
||||
Recorder: recorder,
|
||||
}, a.logger)
|
||||
err = conn.Register(ctx, deviceID, token)
|
||||
credentialUnlock()
|
||||
if err != nil {
|
||||
a.logger.Error("WS 连接失败", "err", err)
|
||||
if ws.IsInvalidTokenError(err) && !invalidTokenRetried {
|
||||
invalidTokenRetried = true
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeConnecting, "消息凭证被拒绝,正在重新获取一次新凭证")
|
||||
continue
|
||||
}
|
||||
if ws.IsConnectLimitError(err) {
|
||||
a.setRuntimeState(RuntimeReconnecting, "消息服务连接数受限,正在限速重试")
|
||||
if sleepCtx(ctx, withRetryJitter(30*time.Second)) != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
continue
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.connFailures++
|
||||
failures := a.connFailures
|
||||
a.mu.Unlock()
|
||||
if ws.IsInvalidTokenError(err) || ws.IsAuthenticationError(err) {
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试")
|
||||
if failures >= MaxConnectionFailures {
|
||||
if err := a.handleMaxFailures(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if sleepCtx(ctx, a.retryDelay("ws_dial")) != nil {
|
||||
return ctx.Err()
|
||||
_ = conn.Close()
|
||||
a.logger.Error("WS 注册失败", "err", err)
|
||||
if retryErr := a.handleWSConnectFailure(ctx, err, &invalidTokenRetried); retryErr != nil {
|
||||
return retryErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
@@ -494,11 +466,13 @@ func (a *Account) Run(parent context.Context) error {
|
||||
|
||||
// 正常 close 的 async-for 会直接进入下一轮,不计任何失败。
|
||||
if recvErr == nil {
|
||||
a.clearConnectionToken(ctx)
|
||||
a.setRuntimeState(RuntimeReconnecting, "消息连接已结束,正在重新连接")
|
||||
continue
|
||||
}
|
||||
|
||||
if isEstablishedNetworkError(recvErr) {
|
||||
a.clearConnectionToken(ctx)
|
||||
a.mu.Lock()
|
||||
a.networkFailures++
|
||||
networkFailures := a.networkFailures
|
||||
@@ -530,7 +504,7 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.connFailures++
|
||||
failures := a.connFailures
|
||||
a.mu.Unlock()
|
||||
if time.Since(attemptStartedAt) < 15*time.Second {
|
||||
if time.Since(connectedAt) < 15*time.Second {
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,稍后自动重连")
|
||||
@@ -548,6 +522,67 @@ func (a *Account) Run(parent context.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Account) wsRecorder() func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
|
||||
if a.store == nil || a.store.WSMessages == nil {
|
||||
return nil
|
||||
}
|
||||
return func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
|
||||
if err := a.store.WSMessages.Add(context.Background(), db.WSMessage{
|
||||
CookieID: a.CookieID,
|
||||
Direction: direction,
|
||||
RawText: rawText,
|
||||
ParsedJSON: parsedJSON,
|
||||
MessageKind: "",
|
||||
ParseStatus: parseStatus,
|
||||
Error: errMsg,
|
||||
}); err != nil {
|
||||
a.logger.Error("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Account) handleWSConnectFailure(ctx context.Context, err error, invalidTokenRetried *bool) error {
|
||||
if ws.IsInvalidTokenError(err) && !*invalidTokenRetried {
|
||||
*invalidTokenRetried = true
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeConnecting, "消息凭证被拒绝,正在重新获取一次新凭证")
|
||||
return nil
|
||||
}
|
||||
if ws.IsConnectLimitError(err) {
|
||||
a.setRuntimeState(RuntimeReconnecting, "消息服务连接数受限,正在限速重试")
|
||||
return sleepCtx(ctx, withRetryJitter(30*time.Second))
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.connFailures++
|
||||
failures := a.connFailures
|
||||
a.mu.Unlock()
|
||||
if ws.IsInvalidTokenError(err) || ws.IsAuthenticationError(err) {
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试")
|
||||
if failures >= MaxConnectionFailures {
|
||||
return a.handleMaxFailures(ctx)
|
||||
}
|
||||
return sleepCtx(ctx, a.retryDelay("ws_connect"))
|
||||
}
|
||||
|
||||
// acquireFreshConnectionToken mirrors the official web message client:
|
||||
// authTokenCallback obtains a fresh login.token result before every WebSocket
|
||||
// loginV2/reConnect and the returned accessToken is used only for that /reg.
|
||||
func (a *Account) acquireFreshConnectionToken(ctx context.Context) (string, string, error) {
|
||||
return a.refreshToken(ctx)
|
||||
}
|
||||
|
||||
// clearConnectionToken ends the lifetime of the token used by the previous
|
||||
// WebSocket attempt. The page-runtime device ID remains stable until a Cookie
|
||||
// update maps to an official page reload.
|
||||
func (a *Account) clearConnectionToken(ctx context.Context) {
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
|
||||
// Stop 优雅停止。
|
||||
func (a *Account) Stop() {
|
||||
a.mu.Lock()
|
||||
@@ -768,6 +803,7 @@ func (a *Account) tryAPIRenew(ctx context.Context) bool {
|
||||
}
|
||||
updated := false
|
||||
if res.NewCookies != "" && res.NewCookies != cookieStr {
|
||||
a.persistRenewCookieSnapshot(ctx, cookieStr, res.NewCookies, res.SetCookies)
|
||||
updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期")
|
||||
}
|
||||
if res.Success {
|
||||
@@ -785,6 +821,25 @@ func (a *Account) tryAPIRenew(ctx context.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *Account) persistRenewCookieSnapshot(ctx context.Context, oldCookies, newCookies string, setCookies []string) {
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
detail, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
|
||||
if err != nil || detail == nil {
|
||||
return
|
||||
}
|
||||
snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
|
||||
if len(snapshot) == 0 {
|
||||
snapshot = cookierefresh.SnapshotFromCookieString(oldCookies, ".goofish.com")
|
||||
}
|
||||
snapshot = cookierefresh.ApplySetCookies(snapshot, renew.SilentHasLoginURL, setCookies, time.Now())
|
||||
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("保存接口续期 Cookie 快照失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// adoptRecoveredCookie 统一接收“轻量检查/接口续期/浏览器恢复”拿到的新 Cookie。
|
||||
// Cookie 变更意味着旧 accessToken 与 session 绑定关系失效,必须清 token 缓存,
|
||||
// 让下一轮 acquireToken 使用新 Cookie 重新派生凭证。
|
||||
@@ -799,6 +854,7 @@ func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source s
|
||||
return false
|
||||
}
|
||||
a.replaceCookieStr(newCookies)
|
||||
a.rotateDeviceID(newCookies)
|
||||
a.clearCurrentToken()
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, newCookies); err != nil {
|
||||
@@ -906,8 +962,8 @@ func (a *Account) recordShortDisconnect(connectedDuration time.Duration) bool {
|
||||
}
|
||||
|
||||
// refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。
|
||||
// 成功时把 token + device_id 缓存到 DB(saveTokenCache),供进程重启复用与
|
||||
// 稳态重连时跳过 mtop(acquireToken 命中缓存即直接返回)。
|
||||
// 成功时记录 token 的服务端过期时间并保持 device_id 持久化,但连接流程
|
||||
// 不会复用该 token;下一次 loginV2/reConnect 仍会重新调用本方法。
|
||||
func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
|
||||
return a.refreshTokenWithMinGap(ctx, false)
|
||||
}
|
||||
@@ -1008,8 +1064,20 @@ func (a *Account) adoptTokenResponseCookies(ctx context.Context, cookieStr strin
|
||||
}
|
||||
a.replaceCookieStr(res.UpdatedCookies)
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, res.UpdatedCookies); err != nil {
|
||||
a.logger.Error("token 响应后保存 cookie 失败", "cookie_id", a.CookieID, "err", err)
|
||||
detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID)
|
||||
if detailErr == nil && detail != nil {
|
||||
snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
|
||||
if len(snapshot) == 0 {
|
||||
snapshot = cookierefresh.SnapshotFromCookieString(cookieStr, ".goofish.com")
|
||||
}
|
||||
snapshot = cookierefresh.ReconcileSnapshotWithCookieString(snapshot, res.UpdatedCookies)
|
||||
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
|
||||
detailErr = a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.UpdatedCookies, metadata, time.Now().Unix())
|
||||
} else {
|
||||
detailErr = a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, res.UpdatedCookies)
|
||||
}
|
||||
if detailErr != nil {
|
||||
a.logger.Error("token 响应后保存 cookie 失败", "cookie_id", a.CookieID, "err", detailErr)
|
||||
}
|
||||
}
|
||||
return res.UpdatedCookies
|
||||
@@ -1062,39 +1130,23 @@ func (a *Account) tokenCaptchaCooldownRemaining() time.Duration {
|
||||
return remaining
|
||||
}
|
||||
|
||||
// acquireToken 取用于 WS /reg 的 accessToken:缓存命中且未过期则跳过 mtop(降低风控
|
||||
// 与瞬时失败影响),否则调 refreshToken 重新派生并落库缓存。
|
||||
//
|
||||
// 设计:稳态重连时复用未过期缓存 token,避免每次重连都打 mtop(降低风控触发)。
|
||||
// 缓存 token 若已被服务端失效,dial 后会短连接断开 → clearTokenCache → 下轮重新派生,自愈。
|
||||
// acquireToken is kept for internal callers and tests, but intentionally does
|
||||
// not reuse the persisted accessToken. Official web reconnects always invoke
|
||||
// the login.token API before /reg.
|
||||
func (a *Account) acquireToken(ctx context.Context) (string, string, error) {
|
||||
return a.acquireTokenWithMinGap(ctx, false)
|
||||
}
|
||||
|
||||
// acquireRuntimeToken 对齐参考主循环:网络重连时只要内存 token 仍存在就直接
|
||||
// 复用;只有认证分支明确清空它后,才重新检查数据库缓存或调用 Token API。
|
||||
// acquireRuntimeToken is retained as a compatibility wrapper for focused
|
||||
// tests and older internal callers. It follows the same fresh-token rule.
|
||||
func (a *Account) acquireRuntimeToken(ctx context.Context) (string, string, error) {
|
||||
a.mu.Lock()
|
||||
token := a.currentToken
|
||||
cookieStr := a.CookieStr
|
||||
a.mu.Unlock()
|
||||
if strings.TrimSpace(token) != "" {
|
||||
return token, cookieStr, nil
|
||||
}
|
||||
return a.acquireToken(ctx)
|
||||
return a.acquireFreshConnectionToken(ctx)
|
||||
}
|
||||
|
||||
func (a *Account) acquireTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) {
|
||||
if token, ok := a.cachedTokenIfFresh(ctx); ok {
|
||||
a.mu.Lock()
|
||||
a.currentToken = token
|
||||
a.lastTokenRefresh = time.Now()
|
||||
a.lastTokenStatus = tokenRefreshSuccessFromCache
|
||||
cookieStr := a.CookieStr
|
||||
a.mu.Unlock()
|
||||
a.logger.Info("使用缓存的 accessToken,跳过 mtop 刷新")
|
||||
return token, cookieStr, nil
|
||||
}
|
||||
// Invalidate any access token left by an older process/attempt before asking
|
||||
// MTOP for the token that will be bound to this connection.
|
||||
a.clearTokenCache(ctx)
|
||||
return a.refreshToken(ctx)
|
||||
}
|
||||
|
||||
@@ -1130,39 +1182,9 @@ func tokenFailureIsNonCounted(status string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// cachedTokenIfFresh 返回未过期的缓存 accessToken。无缓存 / 已过期返回 ok=false。
|
||||
func (a *Account) cachedTokenIfFresh(ctx context.Context) (string, bool) {
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return "", false
|
||||
}
|
||||
tk, err := a.store.Tokens.Get(ctx, a.CookieID)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
a.mu.Lock()
|
||||
cookieStr := a.CookieStr
|
||||
a.mu.Unlock()
|
||||
expectedFingerprint := credentialCookieFingerprint(cookieStr)
|
||||
if tk.AccessToken == "" || tk.ExpireAt <= time.Now().Unix() ||
|
||||
tk.CookieFingerprint == "" || tk.CookieFingerprint != expectedFingerprint {
|
||||
// 参考实现发现过期缓存后立即删除整行,再进入标准 token 请求。
|
||||
if tk.AccessToken != "" {
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
// 命中缓存时同步复用其 device_id,保证 token 与 /reg.did 一致。
|
||||
if tk.DeviceID != "" {
|
||||
a.mu.Lock()
|
||||
a.deviceID = tk.DeviceID
|
||||
a.mu.Unlock()
|
||||
}
|
||||
return tk.AccessToken, true
|
||||
}
|
||||
|
||||
// saveTokenCache uses the expiry returned by the token API. A response without
|
||||
// a usable accessTokenExpiredTime remains valid for the current process only;
|
||||
// it is deliberately not assigned a guessed multi-hour lifetime.
|
||||
// saveTokenCache records the server expiry and current page-runtime identity.
|
||||
// It is diagnostic state only: acquireToken never reads the accessToken back
|
||||
// for a later WebSocket registration.
|
||||
func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, cookieStr string) {
|
||||
if a.store == nil || a.store.Tokens == nil || accessToken == "" {
|
||||
return
|
||||
@@ -1206,6 +1228,7 @@ func (a *Account) reloadCookieFromDB(ctx context.Context) bool {
|
||||
}
|
||||
a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID)
|
||||
a.replaceCookieStr(d.Value)
|
||||
a.rotateDeviceID(d.Value)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
a.mu.Lock()
|
||||
@@ -1322,6 +1345,16 @@ func (a *Account) replaceCookieStr(cookieStr string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Account) rotateDeviceID(cookieStr string) {
|
||||
userID := protocol.TransCookies(cookieStr)["unb"]
|
||||
a.mu.Lock()
|
||||
if userID == "" {
|
||||
userID = a.UserID
|
||||
}
|
||||
a.deviceID = protocol.GenerateDeviceID(userID)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。
|
||||
func (a *Account) UpdateCookie(cookieStr string) {
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
@@ -1346,9 +1379,15 @@ func (a *Account) UpdateCookie(cookieStr string) {
|
||||
}
|
||||
}
|
||||
a.replaceCookieStr(cookieStr)
|
||||
// Updating credentials does not close a healthy connection. Clearing the
|
||||
// in-memory and persisted token makes the next reconnect authenticate from
|
||||
// this Cookie snapshot instead of reusing a token issued for the old one.
|
||||
a.rotateDeviceID(cookieStr)
|
||||
// 官网静默续期成功会 location.reload()。本地收到外部 Cookie 更新时关闭
|
||||
// 健康连接,让主循环立即用新 Cookie、新 device ID 和新 token 重建。
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(context.Background())
|
||||
a.mu.Lock()
|
||||
conn := a.conn
|
||||
a.mu.Unlock()
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}
|
||||
@@ -275,8 +275,8 @@ func TestTryAPIRenewSuccessShortCircuitsRecovery(t *testing.T) {
|
||||
if saved != "unb=123; _m_h5_tk=tk_2;" {
|
||||
t.Fatalf("DB cookie 未更新: %q", saved)
|
||||
}
|
||||
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
|
||||
t.Fatalf("接口续期后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
|
||||
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" {
|
||||
t.Fatalf("接口续期后应清 token;数据库中的旧 device ID 不再参与运行时身份: tk=%+v err=%v", tk, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,8 +306,8 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
|
||||
if saved != "unb=123; _m_h5_tk=partial;" {
|
||||
t.Fatalf("部分 cookie 应先保存到 DB: %q", saved)
|
||||
}
|
||||
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
|
||||
t.Fatalf("部分 cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
|
||||
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" {
|
||||
t.Fatalf("部分 cookie 更新后应清 token: tk=%+v err=%v", tk, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,11 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
|
||||
if err != nil || cfg == nil || !cfg.AIEnabled {
|
||||
return nil, nil // 未启用 AI
|
||||
}
|
||||
// AI 设置面向砍价场景。普通未命中消息继续交给默认回复,避免 AI
|
||||
// 抢答问候、售后等与砍价无关的消息。
|
||||
if !bargainMessageRe.MatchString(strings.ToLower(m.Text)) {
|
||||
return nil, nil
|
||||
}
|
||||
aiCfg, err := a.globalAIConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取全局 AI 配置失败: %w", err)
|
||||
|
||||
@@ -76,7 +76,7 @@ func TestAIReply_DisabledReturnsNil(t *testing.T) {
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
|
||||
// 无配置记录 → 未启用 → nil。
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
|
||||
if err != nil || res != nil {
|
||||
t.Fatalf("未配置应返回 nil,nil: res=%+v err=%v", res, err)
|
||||
}
|
||||
@@ -97,7 +97,7 @@ func TestAIReply_NoAPIKeyReturnsNil(t *testing.T) {
|
||||
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
|
||||
if err != nil || res != nil {
|
||||
t.Fatalf("无 APIKey 应返回 nil,nil: res=%+v err=%v", res, err)
|
||||
}
|
||||
@@ -137,7 +137,7 @@ func TestAIReply_HTTPErrorDegrades(t *testing.T) {
|
||||
s.Settings.Set(ctx, "ai_api_url", srv.URL)
|
||||
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
res, err := a.Reply(ctx, chatMsg("还能优惠吗", "item1", "chat1"))
|
||||
if err == nil {
|
||||
t.Fatalf("HTTP 500 应返回错误,got res=%+v", res)
|
||||
}
|
||||
@@ -165,7 +165,7 @@ func TestAIReply_EmptyChoicesReturnsNil(t *testing.T) {
|
||||
s.Settings.Set(ctx, "ai_api_url", srv.URL)
|
||||
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
res, err := a.Reply(ctx, chatMsg("可以便宜一点吗", "item1", "chat1"))
|
||||
if err != nil || res != nil {
|
||||
t.Fatalf("空 choices 应返回 nil,nil: res=%+v err=%v", res, err)
|
||||
}
|
||||
@@ -182,7 +182,7 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) {
|
||||
s.Settings.Set(ctx, "ai_api_url", srv.URL)
|
||||
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
res, err := a.Reply(ctx, chatMsg("最低多少钱", "item1", "chat1"))
|
||||
if err != nil {
|
||||
t.Fatalf("成功调用不应报错: %v", err)
|
||||
}
|
||||
@@ -191,6 +191,20 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIReply_NonBargainMessageFallsThrough(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
|
||||
s.Settings.Set(ctx, "ai_api_key", "sk-test")
|
||||
s.Settings.Set(ctx, "ai_api_url", "http://127.0.0.1:1")
|
||||
|
||||
res, err := NewAIReplier("cid", s, nil).Reply(ctx, chatMsg("在吗,什么时候发货", "item1", "chat1"))
|
||||
if err != nil || res != nil {
|
||||
t.Fatalf("非砍价消息应交给默认回复: res=%+v err=%v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGlobalAIConfig 默认值兜底 + 显式设置覆盖。
|
||||
func TestGlobalAIConfig(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
|
||||
@@ -118,8 +118,10 @@ func (s *statusMtop) CheckLoginStatusContext(context.Context, string) (*mtop.Log
|
||||
return s.result, s.err
|
||||
}
|
||||
|
||||
// TestAcquireToken_CacheHitSkipsMtop 缓存命中且未过期时跳过 mtop 调用。
|
||||
func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
|
||||
// TestAcquireToken_CacheHitStillFetchesFreshToken matches the official web
|
||||
// client: every connection attempt calls login.token even when a persisted
|
||||
// token has not reached its advertised expiry.
|
||||
func TestAcquireToken_CacheHitStillFetchesFreshToken(t *testing.T) {
|
||||
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
|
||||
acc, _, store, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
@@ -129,11 +131,11 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("acquireToken: %v", err)
|
||||
}
|
||||
if token != "cached-tok" {
|
||||
t.Fatalf("应使用缓存 token,got %s", token)
|
||||
if token != "tok-mtop" {
|
||||
t.Fatalf("应使用新获取 token,got %s", token)
|
||||
}
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
|
||||
t.Fatalf("缓存命中不应调用 mtop,got %d", calls)
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
|
||||
t.Fatalf("每次连接都应调用 mtop,got %d", calls)
|
||||
}
|
||||
if !strings.Contains(cookies, "_m_h5_tk=tk_1") {
|
||||
t.Fatalf("缓存命中应返回其绑定的 Cookie: %q", cookies)
|
||||
@@ -160,7 +162,7 @@ func TestAcquireToken_RejectsCacheBoundToDifferentCookie(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing.T) {
|
||||
func TestAcquireRuntimeTokenReplacesMemoryToken(t *testing.T) {
|
||||
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
|
||||
acc, _, store, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
@@ -168,11 +170,11 @@ func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing.
|
||||
_ = store.Tokens.Clear(context.Background(), "cid")
|
||||
|
||||
token, _, err := acc.acquireRuntimeToken(context.Background())
|
||||
if err != nil || token != "runtime-token" {
|
||||
if err != nil || token != "tok-mtop" {
|
||||
t.Fatalf("runtime token=%q err=%v", token, err)
|
||||
}
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
|
||||
t.Fatalf("网络重连复用内存 token 时不应调用 mtop,calls=%d", calls)
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
|
||||
t.Fatalf("网络重连应获取新 token,calls=%d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,6 +220,7 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
|
||||
oldDeviceID := acc.deviceID
|
||||
saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
|
||||
res := acc.tryLoginStatusCheck(context.Background())
|
||||
if !res.recovered || res.riskRequired {
|
||||
@@ -230,8 +233,8 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
|
||||
if err != nil || saved != newCookie {
|
||||
t.Fatalf("DB Cookie 未更新: got %q err=%v", saved, err)
|
||||
}
|
||||
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
|
||||
t.Fatalf("Cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
|
||||
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID {
|
||||
t.Fatalf("Cookie 更新后应清 token 并为页面重载轮换 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,6 +269,7 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
defer cleanup()
|
||||
// 预置旧 session 的 token 缓存。
|
||||
oldDeviceID := acc.deviceID
|
||||
saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
|
||||
// 外部更新 DB cookie(模拟重新扫码),userID=0 复用现有 user_id。
|
||||
newCookie := "unb=123; _m_h5_tk=newtk_2; sgcookie=abc"
|
||||
@@ -276,9 +280,9 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
|
||||
if got := acc.CurrentCookieStr(); got != newCookie {
|
||||
t.Fatalf("应采纳 DB 新 cookie,got %s", got)
|
||||
}
|
||||
// 新 cookie 对应新 session,旧 token 应清除但 device ID 必须保留。
|
||||
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
|
||||
t.Fatalf("cookie 变更后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
|
||||
// 新 cookie 对应官网页面重载:旧 token 清除,运行时 device ID 轮换。
|
||||
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID {
|
||||
t.Fatalf("cookie 变更后应清 token 并轮换运行时 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+95
-25
@@ -3,6 +3,7 @@ package engine
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
@@ -58,10 +59,33 @@ func (f *fakeFailTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, str
|
||||
return nil, f.err
|
||||
}
|
||||
|
||||
type sequencedTokenMtop struct {
|
||||
fakeRunMtop
|
||||
mu sync.Mutex
|
||||
devices []string
|
||||
cookies []string
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *sequencedTokenMtop) RefreshTokenWithDeviceIDContext(_ context.Context, cookieStr, deviceID string) (*mtop.RefreshResult, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.calls++
|
||||
s.devices = append(s.devices, deviceID)
|
||||
s.cookies = append(s.cookies, cookieStr)
|
||||
return &mtop.RefreshResult{
|
||||
AccessToken: fmt.Sprintf("fresh-%d", s.calls),
|
||||
AccessTokenExpireAt: time.Now().Add(time.Hour).Unix(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// fakeWSConn 实现 WSConn,可控地投递消息并阻塞到 ctx 取消。
|
||||
type fakeWSConn struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
registerErr error
|
||||
registeredDID string
|
||||
registeredTok string
|
||||
sentTexts []string
|
||||
sentImages []string
|
||||
heartbeatDone chan struct{}
|
||||
@@ -72,6 +96,15 @@ type fakeWSConn struct {
|
||||
recvErr error
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) Register(_ context.Context, deviceID, accessToken string) error {
|
||||
f.mu.Lock()
|
||||
f.registeredDID = deviceID
|
||||
f.registeredTok = accessToken
|
||||
err := f.registerErr
|
||||
f.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
|
||||
<-ctx.Done()
|
||||
if f.heartbeatDone != nil {
|
||||
@@ -221,13 +254,12 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
|
||||
// 初始 token 应通过 ws.Config.AccessToken 传给 Dial(非 SetAccessToken)。
|
||||
d := acc.wsDialer.(*fakeDialer)
|
||||
d.mu.Lock()
|
||||
gotToken := d.lastCfg.AccessToken == "tok-1"
|
||||
d.mu.Unlock()
|
||||
// token 必须在握手成功后通过 Register 发送,而不是在 Dial 前获得。
|
||||
conn.mu.Lock()
|
||||
gotToken := conn.registeredTok == "tok-1"
|
||||
conn.mu.Unlock()
|
||||
if !gotToken {
|
||||
t.Fatal("Dial 未收到 ws.Config.AccessToken=tok-1")
|
||||
t.Fatal("Register 未收到 token=tok-1")
|
||||
}
|
||||
|
||||
// 取消 ctx → Run 应退出。
|
||||
@@ -272,7 +304,7 @@ func TestRun_DialFailureIncrementsFailures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并复用当前内存 token。
|
||||
// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并重新获取 token。
|
||||
func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
|
||||
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
|
||||
acc, _, _, cleanup := newRunAccount(t, mtopClient)
|
||||
@@ -311,12 +343,52 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("重连后 ctx 取消 Run 未退出")
|
||||
}
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
|
||||
t.Fatalf("正常重连应复用内存 token,不应重复请求 mtop: calls=%d", calls)
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
|
||||
t.Fatalf("正常重连应重新请求 mtop: calls=%d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) {
|
||||
func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
|
||||
mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "unused"}}
|
||||
acc, _, _, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
dialer := &fakeDialer{results: []dialResult{
|
||||
{conn: &fakeWSConn{recvBlock: false}},
|
||||
{conn: &fakeWSConn{recvBlock: true}},
|
||||
}}
|
||||
acc.wsDialer = dialer
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
waitForDialCalls(t, dialer, 2)
|
||||
cancel()
|
||||
<-done
|
||||
|
||||
dialer.mu.Lock()
|
||||
conns := append([]*fakeWSConn(nil), dialer.conns...)
|
||||
dialer.mu.Unlock()
|
||||
if len(conns) < 2 {
|
||||
t.Fatalf("dial conns=%d want>=2", len(conns))
|
||||
}
|
||||
conns[0].mu.Lock()
|
||||
firstToken := conns[0].registeredTok
|
||||
conns[0].mu.Unlock()
|
||||
conns[1].mu.Lock()
|
||||
secondToken := conns[1].registeredTok
|
||||
conns[1].mu.Unlock()
|
||||
if firstToken != "fresh-1" || secondToken != "fresh-2" {
|
||||
t.Fatalf("reconnect tokens=%v", []string{firstToken, secondToken})
|
||||
}
|
||||
mtopClient.mu.Lock()
|
||||
devices := append([]string(nil), mtopClient.devices...)
|
||||
mtopClient.mu.Unlock()
|
||||
if len(devices) != 2 || devices[0] == "" || devices[0] != devices[1] {
|
||||
t.Fatalf("device IDs must remain stable: %v", devices)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_EstablishedNetworkErrorClearsConnectionToken(t *testing.T) {
|
||||
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
|
||||
acc, _, store, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
@@ -340,15 +412,15 @@ func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) {
|
||||
currentToken := acc.currentToken
|
||||
networkFailures := acc.networkFailures
|
||||
acc.mu.Unlock()
|
||||
if networkFailures != 1 || currentToken != "tok-1" {
|
||||
if networkFailures != 1 || currentToken != "" {
|
||||
cancel()
|
||||
<-done
|
||||
t.Fatalf("网络断线不应清空内存 token: failures=%d token=%q", networkFailures, currentToken)
|
||||
t.Fatalf("网络断线应结束当前 token 生命周期: failures=%d token=%q", networkFailures, currentToken)
|
||||
}
|
||||
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" {
|
||||
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "" {
|
||||
cancel()
|
||||
<-done
|
||||
t.Fatalf("网络断线不应删除 token 缓存: cached=%+v err=%v", cached, err)
|
||||
t.Fatalf("网络断线应清除 token 缓存: cached=%+v err=%v", cached, err)
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
@@ -366,7 +438,7 @@ func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) {
|
||||
acc, _, _, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
dialer := &fakeDialer{results: []dialResult{
|
||||
{err: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}},
|
||||
{conn: &fakeWSConn{registerErr: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}}},
|
||||
{conn: &fakeWSConn{recvBlock: true}},
|
||||
}}
|
||||
acc.wsDialer = dialer
|
||||
@@ -384,7 +456,7 @@ func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) {
|
||||
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "token"}}
|
||||
mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "token"}}
|
||||
acc, _, store, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
newCookie := "unb=123; _m_h5_tk=db-renewed_2; cookie2=new"
|
||||
@@ -406,16 +478,13 @@ func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) {
|
||||
cancel()
|
||||
<-done
|
||||
|
||||
dialer.mu.Lock()
|
||||
configs := append([]ws.Config(nil), dialer.configs...)
|
||||
dialer.mu.Unlock()
|
||||
if len(configs) < 2 {
|
||||
t.Fatalf("dial configs=%d want>=2", len(configs))
|
||||
mtopClient.mu.Lock()
|
||||
cookies := append([]string(nil), mtopClient.cookies...)
|
||||
mtopClient.mu.Unlock()
|
||||
if len(cookies) < 2 || cookies[1] != newCookie {
|
||||
t.Fatalf("second token Cookie=%v want=%q", cookies, newCookie)
|
||||
}
|
||||
if configs[1].CookieStr != newCookie {
|
||||
t.Fatalf("second dial Cookie=%q want=%q", configs[1].CookieStr, newCookie)
|
||||
}
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
|
||||
if calls := mtopClient.calls; calls != 2 {
|
||||
t.Fatalf("Cookie change should invalidate token for reconnect, calls=%d", calls)
|
||||
}
|
||||
}
|
||||
@@ -462,6 +531,7 @@ func TestRun_DisabledAccountExits(t *testing.T) {
|
||||
func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
|
||||
defer cleanup()
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: &fakeWSConn{recvBlock: true}}}}
|
||||
h := &failingRefreshHandler{}
|
||||
acc.handler = h
|
||||
acc.mu.Lock()
|
||||
|
||||
@@ -597,15 +597,15 @@ func (n *Notifier) sendTelegram(cfg map[string]any, message string) error {
|
||||
func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
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", "")
|
||||
useTLS := parseConfigBool(n.configOrSetting(ctx, cfg, "smtp_use_tls", "true"), true)
|
||||
useSSL := parseConfigBool(n.configOrSetting(ctx, cfg, "smtp_use_ssl", "false"), false)
|
||||
fromAddress := n.configOrSetting(ctx, cfg, "smtp_from_address", "")
|
||||
fromName := n.configOrSetting(ctx, cfg, "smtp_from_name", "")
|
||||
legacyFrom := n.configOrSetting(ctx, cfg, "smtp_from", "")
|
||||
server := n.smtpConfigValue(ctx, cfg, "smtp_server", "")
|
||||
port := n.smtpConfigValue(ctx, cfg, "smtp_port", "587")
|
||||
user := n.smtpConfigValue(ctx, cfg, "smtp_user", "")
|
||||
pass := n.smtpConfigValue(ctx, cfg, "smtp_password", "")
|
||||
useTLS := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_tls", "true"), true)
|
||||
useSSL := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_ssl", "false"), false)
|
||||
fromAddress := n.smtpConfigValue(ctx, cfg, "smtp_from_address", "")
|
||||
fromName := n.smtpConfigValue(ctx, cfg, "smtp_from_name", "")
|
||||
legacyFrom := n.smtpConfigValue(ctx, cfg, "smtp_from", "")
|
||||
to := strOr(cfg, "to_email", strOr(cfg, "email", ""))
|
||||
if server == "" || user == "" || to == "" {
|
||||
return fmt.Errorf("邮件配置不完整:请配置系统 SMTP 或在邮件渠道中覆盖 SMTP,并填写收件邮箱")
|
||||
@@ -751,6 +751,27 @@ func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key,
|
||||
return fallbackValue
|
||||
}
|
||||
|
||||
// smtpConfigValue keeps legacy per-field fallback behavior for existing rows,
|
||||
// while new rows use an explicit all-system or all-channel SMTP mode.
|
||||
func (n *Notifier) smtpConfigValue(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
|
||||
modeValue, hasExplicitMode := cfg["use_custom_smtp"]
|
||||
if !hasExplicitMode {
|
||||
return n.configOrSetting(ctx, cfg, key, fallbackValue)
|
||||
}
|
||||
if parseConfigBool(fmt.Sprintf("%v", modeValue), false) {
|
||||
if value := strings.TrimSpace(strOr(cfg, key, "")); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
if n.store != nil && n.store.Settings != nil {
|
||||
if value, err := n.store.Settings.Get(ctx, key); err == nil && strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
|
||||
// postJSON 通用 JSON POST。
|
||||
func (n *Notifier) postJSON(url string, payload any) error {
|
||||
body, err := json.Marshal(payload)
|
||||
|
||||
@@ -568,6 +568,33 @@ func TestSendEmail_UsesSystemSMTPFallback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPConfigValueUsesExclusiveExplicitModes(t *testing.T) {
|
||||
store, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if err := store.Settings.Set(ctx, "smtp_server", "system.example.com"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n := New("cid", store, nil)
|
||||
|
||||
if got := n.smtpConfigValue(ctx, map[string]any{
|
||||
"use_custom_smtp": false,
|
||||
"smtp_server": "stale-channel.example.com",
|
||||
}, "smtp_server", ""); got != "system.example.com" {
|
||||
t.Fatalf("system mode mixed in channel override: %q", got)
|
||||
}
|
||||
if got := n.smtpConfigValue(ctx, map[string]any{
|
||||
"use_custom_smtp": true,
|
||||
}, "smtp_server", ""); got != "" {
|
||||
t.Fatalf("custom mode inherited system value: %q", got)
|
||||
}
|
||||
if got := n.smtpConfigValue(ctx, map[string]any{
|
||||
"smtp_server": "legacy-channel.example.com",
|
||||
}, "smtp_server", ""); got != "legacy-channel.example.com" {
|
||||
t.Fatalf("legacy channel override compatibility lost: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendEmail_IncompleteConfig 配置不完整应报错。
|
||||
func TestSendEmail_IncompleteConfig(t *testing.T) {
|
||||
n := New("cid", nil, nil)
|
||||
|
||||
@@ -46,6 +46,10 @@ type AccountStarter interface {
|
||||
Start(ctx context.Context, cookieID, cookieValue string) error
|
||||
}
|
||||
|
||||
type accountRestarter interface {
|
||||
Restart(ctx context.Context, cookieID string) error
|
||||
}
|
||||
|
||||
type BrowserRenewer interface {
|
||||
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
|
||||
CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error)
|
||||
@@ -101,7 +105,9 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
|
||||
go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, true, apiCookieRenewInterval, s.executeAPICookieRenew)
|
||||
// 官网静默插件只在页面/账号运行时启动时执行,不做每小时轮询。保留
|
||||
// 调度器入口供显式兼容配置使用,但默认关闭。
|
||||
go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, false, apiCookieRenewInterval, s.executeAPICookieRenew)
|
||||
go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeBrowserCookieRefresh)
|
||||
}
|
||||
|
||||
@@ -165,8 +171,7 @@ func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account d
|
||||
}
|
||||
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 {
|
||||
if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, account.MetadataJSON, time.Now().Unix()); err != nil {
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated, time.Since(started))
|
||||
return
|
||||
}
|
||||
@@ -195,7 +200,13 @@ func (s *Scheduler) executeAPICookieRenew(ctx context.Context) {
|
||||
|
||||
func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
|
||||
credentialUnlock := s.store.LockAccountCredentials(account.ID)
|
||||
defer credentialUnlock()
|
||||
shouldRestart := false
|
||||
defer func() {
|
||||
credentialUnlock()
|
||||
if shouldRestart {
|
||||
s.restartAccount(ctx, account.ID)
|
||||
}
|
||||
}()
|
||||
account = s.reloadRenewalAccount(ctx, account)
|
||||
started := time.Now()
|
||||
res, err := s.renewAPI(ctx, account.Value)
|
||||
@@ -215,10 +226,17 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
stepDetails = append(stepDetails, fmt.Sprintf("result: success=%v skipped=%v reason=%s", res.Success, res.Skipped, res.SkipReason))
|
||||
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)) {
|
||||
snapshot := cookierefresh.SnapshotFromMetadata(account.MetadataJSON)
|
||||
if len(snapshot) == 0 {
|
||||
snapshot = cookierefresh.SnapshotFromCookieString(account.Value, ".goofish.com")
|
||||
}
|
||||
snapshot = cookierefresh.ApplySetCookies(snapshot, apirenew.SilentHasLoginURL, res.SetCookies, time.Now())
|
||||
metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, snapshot)
|
||||
if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, metadata) {
|
||||
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: res.RequestCount})
|
||||
return
|
||||
}
|
||||
shouldRestart = account.Enabled && res.Success
|
||||
}
|
||||
status := "failed"
|
||||
if res.Skipped {
|
||||
@@ -288,7 +306,13 @@ func (s *Scheduler) executeBrowserCookieRefresh(ctx context.Context) {
|
||||
|
||||
func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, account db.RenewalAccount, schedule db.CookieRefreshSchedule) {
|
||||
credentialUnlock := s.store.LockAccountCredentials(account.ID)
|
||||
defer credentialUnlock()
|
||||
shouldRestart := false
|
||||
defer func() {
|
||||
credentialUnlock()
|
||||
if shouldRestart {
|
||||
s.restartAccount(ctx, account.ID)
|
||||
}
|
||||
}()
|
||||
account = s.reloadRenewalAccount(ctx, account)
|
||||
started := time.Now()
|
||||
if s.browser == nil {
|
||||
@@ -326,6 +350,8 @@ func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string,
|
||||
s.logger.Warn("cookies_refresh 启动账号失败", "account", account.ID, "err", err)
|
||||
}
|
||||
}
|
||||
} else if len(updated) > 0 {
|
||||
shouldRestart = true
|
||||
}
|
||||
nextExpire := time.Now().Add(browserSuccessDelay()).Unix()
|
||||
schedule.Disabled = false
|
||||
@@ -350,6 +376,16 @@ func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Scheduler) restartAccount(ctx context.Context, cookieID string) {
|
||||
restarter, ok := s.starter.(accountRestarter)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := restarter.Restart(ctx, cookieID); err != nil {
|
||||
s.logger.Warn("Cookie 更新后重启账号失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string) (*apirenew.Result, error) {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@@ -360,7 +360,7 @@ func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)})
|
||||
_, _ = w.Write([]byte(`{"content":{"success":true},"marker":"single-silent"}`))
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}},"marker":"single-silent"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
|
||||
@@ -266,8 +266,8 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r
|
||||
if act.DeliveryCount <= 0 {
|
||||
act.DeliveryCount = 1
|
||||
}
|
||||
if act.DelaySeconds < 0 || act.DelaySeconds > 86400 {
|
||||
return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 86400 秒之间")
|
||||
if act.DelaySeconds < 0 || act.DelaySeconds > 3600 {
|
||||
return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 3600 秒之间")
|
||||
}
|
||||
if act.ConfigJSON == "" {
|
||||
act.ConfigJSON = "{}"
|
||||
|
||||
@@ -92,8 +92,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
delaySeconds := atoiPublishDefault(firstImportString(m, "delay_seconds", "延迟秒"), 0)
|
||||
if delaySeconds < 0 || delaySeconds > 86400 {
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 86400 秒之间"})
|
||||
if delaySeconds < 0 || delaySeconds > 3600 {
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 3600 秒之间"})
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -136,8 +136,8 @@ func decodeCard(r *http.Request) (*db.CardFull, error) {
|
||||
default:
|
||||
return nil, errStr("类型必须为 text、data、image 或 api")
|
||||
}
|
||||
if req.DelaySeconds < 0 || req.DelaySeconds > 86400 {
|
||||
return nil, errStr("延时发货必须在 0 到 86400 秒之间")
|
||||
if req.DelaySeconds < 0 || req.DelaySeconds > 3600 {
|
||||
return nil, errStr("延时发货必须在 0 到 3600 秒之间")
|
||||
}
|
||||
switch req.Type {
|
||||
case "text":
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
// mountCookies 账号 cookie 管理端点。
|
||||
@@ -24,6 +26,8 @@ func (s *Server) mountCookies(r chi.Router) {
|
||||
r.Put("/cookies/{cid}", s.updateCookie)
|
||||
r.Put("/cookies/{cid}/login-info", s.updateCookieLoginInfo)
|
||||
r.Put("/cookies/{cid}/settings", s.updateCookieSettings)
|
||||
r.Get("/cookies/{cid}/long-login", s.getLongLoginSettings)
|
||||
r.Put("/cookies/{cid}/long-login", s.setLongLoginSettings)
|
||||
r.Post("/cookies/{cid}/refresh-profile", s.refreshCookieProfile)
|
||||
r.Get("/cookie/{cid}/details", s.getCookieDetails)
|
||||
r.Put("/cookies/{cid}/status", s.setCookieStatus)
|
||||
@@ -35,6 +39,74 @@ func (s *Server) mountCookies(r chi.Router) {
|
||||
r.Get("/cookies/{cid}/pause-duration", s.getCookiePauseDuration)
|
||||
}
|
||||
|
||||
func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
detail, ok := s.requireCookieOwner(w, r, cid)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result, err := s.CookieRenew.QueryLongLoginSettings(r.Context(), detail.Value)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.QueryLoginSettingsURL); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
detail, ok := s.requireCookieOwner(w, r, cid)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil || req.Enabled == nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
result, err := s.CookieRenew.SetLongLoginSettings(r.Context(), detail.Value, *req.Enabled)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.SetLoginSettingsURL); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieDetail, result *xrenew.LongLoginSettings, requestURL string) error {
|
||||
if result == nil || result.NewCookies == "" || result.NewCookies == detail.Value {
|
||||
return nil
|
||||
}
|
||||
snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
|
||||
if len(snapshot) == 0 {
|
||||
snapshot = cookierefresh.SnapshotFromCookieString(detail.Value, ".goofish.com")
|
||||
}
|
||||
snapshot = cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now())
|
||||
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
|
||||
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); err != nil {
|
||||
s.Logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", err)
|
||||
return err
|
||||
}
|
||||
if s.Store.Tokens != nil {
|
||||
_ = s.Store.Tokens.Clear(ctx, detail.ID)
|
||||
}
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, detail.ID) {
|
||||
if err := s.Manager.Restart(ctx, detail.ID); err != nil {
|
||||
s.Logger.Warn("保存登录信息更新后重启账号失败", "cookie_id", detail.ID, "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type updateCookieSettingsRequest struct {
|
||||
Cookie *string `json:"cookie"`
|
||||
Remark *string `json:"remark"`
|
||||
|
||||
@@ -11,8 +11,68 @@ import (
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
func TestLongLoginSettingsProxyAndPersistCookieSnapshot(t *testing.T) {
|
||||
passport := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("fromSite") != "77" || r.URL.Query().Get("appName") != "xianyu" || r.URL.Query().Get("bizEntrance") != "web" {
|
||||
t.Fatalf("query=%s", r.URL.RawQuery)
|
||||
}
|
||||
if strings.Contains(r.URL.Path, "set") {
|
||||
if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" {
|
||||
t.Fatalf("form=%v err=%v", r.Form, err)
|
||||
}
|
||||
}
|
||||
w.Header().Add("Set-Cookie", "havana_lgc_exp=4102444800000; Domain=.goofish.com; Path=/; Secure; HttpOnly; SameSite=None")
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
|
||||
}))
|
||||
defer passport.Close()
|
||||
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.CookieRenew = xrenew.Service{
|
||||
HTTPClient: passport.Client(),
|
||||
QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
|
||||
SetLoginSettingsURL: passport.URL + "/setLoginSettings.do",
|
||||
}
|
||||
h := srv.Router()
|
||||
session := loginHelper(t, h)
|
||||
|
||||
for _, request := range []*http.Request{
|
||||
httptest.NewRequest(http.MethodGet, "/cookies/acc1/long-login", nil),
|
||||
httptest.NewRequest(http.MethodPut, "/cookies/acc1/long-login", strings.NewReader(`{"enabled":true}`)),
|
||||
} {
|
||||
request.AddCookie(session)
|
||||
recorder := httptest.NewRecorder()
|
||||
h.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("%s status=%d body=%s", request.Method, recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var result xrenew.LongLoginSettings
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || !result.CanOpenLongLogin || !result.Enabled {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
|
||||
if err != nil || !strings.Contains(detail.Value, "havana_lgc_exp=4102444800000") {
|
||||
t.Fatalf("cookie detail=%+v err=%v", detail, err)
|
||||
}
|
||||
snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
|
||||
var longLoginCookie *cookierefresh.BrowserCookie
|
||||
for i := range snapshot {
|
||||
if snapshot[i].Name == "havana_lgc_exp" {
|
||||
longLoginCookie = &snapshot[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if longLoginCookie == nil || longLoginCookie.Domain != ".goofish.com" || !longLoginCookie.Secure || !longLoginCookie.HTTPOnly {
|
||||
t.Fatalf("未保留 Set-Cookie 属性: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListCookies 列表 cookie_id。
|
||||
func TestListCookies(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
|
||||
@@ -78,7 +78,7 @@ func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"name":"API 卡密","type":"api","enabled":true}`,
|
||||
`{"name":"非法类型","type":"unknown","enabled":true}`,
|
||||
`{"name":"延时错误","type":"text","text_content":"x","delay_seconds":86401,"enabled":true}`,
|
||||
`{"name":"延时错误","type":"text","text_content":"x","delay_seconds":3601,"enabled":true}`,
|
||||
`{"name":"空文本","type":"text","text_content":" ","enabled":true}`,
|
||||
`{"name":"空库存","type":"data","data_content":"\n","enabled":true}`,
|
||||
`{"name":"空图片","type":"image","image_url":"","enabled":true}`,
|
||||
|
||||
@@ -267,6 +267,14 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
cookieID := strings.TrimSpace(r.URL.Query().Get("cookie_id"))
|
||||
if cookieID != "" {
|
||||
if _, ok := all[cookieID]; !ok {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
all = map[string]string{cookieID: all[cookieID]}
|
||||
}
|
||||
result := []map[string]any{}
|
||||
for cid := range all {
|
||||
items, _ := s.Store.Items.AllForCookie(r.Context(), cid)
|
||||
@@ -307,6 +315,11 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
|
||||
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
detailCookies := cookieValue
|
||||
if res.UpdatedCookies != "" {
|
||||
detailCookies = res.UpdatedCookies
|
||||
}
|
||||
s.enrichSyncedItemMultiSpec(ctx, client, detailCookies, req.CookieID, res.Items)
|
||||
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
@@ -344,6 +357,11 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
|
||||
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
detailCookies := cookieValue
|
||||
if res.UpdatedCookies != "" {
|
||||
detailCookies = res.UpdatedCookies
|
||||
}
|
||||
s.enrichSyncedItemMultiSpec(ctx, client, detailCookies, req.CookieID, res.Items)
|
||||
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
@@ -391,6 +409,11 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
|
||||
ItemDetail: item.ItemDetail,
|
||||
})
|
||||
if err == nil {
|
||||
if item.IsMultiSpec {
|
||||
if multiErr := s.Store.Items.SetMultiSpec(ctx, cookieID, item.ID, true); multiErr != nil && s.Logger != nil {
|
||||
s.Logger.Warn("保存商品多规格状态失败", "cookie_id", cookieID, "item_id", item.ID, "err", multiErr)
|
||||
}
|
||||
}
|
||||
saved++
|
||||
} else if s.Logger != nil {
|
||||
s.Logger.Warn("保存商品失败", "cookie_id", cookieID, "item_id", item.ID, "err", err)
|
||||
@@ -399,6 +422,27 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
|
||||
return saved
|
||||
}
|
||||
|
||||
func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) {
|
||||
fetcher, ok := client.(mtop.ItemDetailFetcher)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for index := range items {
|
||||
if items[index].IsMultiSpec || s.Store.Items.IsMultiSpec(ctx, cookieID, items[index].ID) {
|
||||
items[index].IsMultiSpec = true
|
||||
continue
|
||||
}
|
||||
isMultiSpec, err := fetcher.DetectItemMultiSpec(ctx, cookies, items[index].ID)
|
||||
if err != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("识别商品多规格状态失败", "cookie_id", cookieID, "item_id", items[index].ID, "err", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
items[index].IsMultiSpec = isMultiSpec
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
|
||||
@@ -357,6 +357,33 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
body := `{"ret":["SUCCESS::调用成功"],"data":{}}`
|
||||
if strings.Contains(req.URL.String(), "mtop.idle.web.xyh.item.list") {
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"id":"multi-item","title":"多规格商品","detailParams":{"itemId":"multi-item"}}}]}}`
|
||||
} else if strings.Contains(req.URL.String(), "mtop.taobao.idle.pc.detail") {
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"multiSKU":true,"skuDO":{"skuList":[{"id":"a"},{"id":"b"}]}}}`
|
||||
}
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
|
||||
}))
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1","page_size":10}`))
|
||||
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())
|
||||
}
|
||||
item, err := store.Items.Get(context.Background(), "acc1", "multi-item")
|
||||
if err != nil || !item.IsMultiSpec {
|
||||
t.Fatalf("item=%+v err=%v", item, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncItemsFromAccountFail mtop 返回非成功 → 502。
|
||||
func TestSyncItemsFromAccountFail(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
@@ -595,6 +622,39 @@ func TestItemCRUD(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestListItemsFiltersByOwnedAccount(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if err := store.Cookies.Save(ctx, "acc2", "unb=456; _m_h5_tk=tk2_1;", admin.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','item-a','商品A'),('acc2','item-b','商品B')`)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/items?cookie_id=acc2", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
var rows []map[string]any
|
||||
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &rows) != nil {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if len(rows) != 1 || rows[0]["cookie_id"] != "acc2" || rows[0]["item_id"] != "item-b" {
|
||||
t.Fatalf("rows=%+v", rows)
|
||||
}
|
||||
|
||||
forbidden := httptest.NewRequest(http.MethodGet, "/items?cookie_id=not-owned", nil)
|
||||
forbidden.AddCookie(cookie)
|
||||
forbiddenRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(forbiddenRec, forbidden)
|
||||
if forbiddenRec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d body=%s", forbiddenRec.Code, forbiddenRec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemGetNotFound 不存在商品 404。
|
||||
func TestItemGetNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
|
||||
@@ -103,7 +103,11 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
defaultCookieID := strings.TrimSpace(r.FormValue("default_cookie_id"))
|
||||
if defaultCookieID != "" && !s.cookieOwnedByUser(r.Context(), sess.UserID, defaultCookieID) {
|
||||
if defaultCookieID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请选择默认发布账号")
|
||||
return
|
||||
}
|
||||
if !s.cookieOwnedByUser(r.Context(), sess.UserID, defaultCookieID) {
|
||||
writeErr(w, http.StatusForbidden, "默认账号不属于当前用户")
|
||||
return
|
||||
}
|
||||
@@ -1111,8 +1115,8 @@ func (s *Server) validatePublishAutomation(ctx context.Context, userID int64, cf
|
||||
if action.DeliveryCount <= 0 {
|
||||
errs = append(errs, prefix+"每件份数必须大于0")
|
||||
}
|
||||
if action.DelaySeconds < 0 || action.DelaySeconds > 86400 {
|
||||
errs = append(errs, prefix+"延迟秒必须在 0 到 86400 之间")
|
||||
if action.DelaySeconds < 0 || action.DelaySeconds > 3600 {
|
||||
errs = append(errs, prefix+"延迟秒必须在 0 到 3600 之间")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -12,9 +13,11 @@ import (
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
const refreshOrderChunkSize = 100
|
||||
const maxSoldOrderPages = 100
|
||||
|
||||
type refreshTarget struct {
|
||||
OrderID string
|
||||
@@ -162,10 +165,6 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Browser == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "浏览器自动化未启用,无法刷新订单")
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
@@ -183,6 +182,32 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
all = map[string]string{cookieID: value}
|
||||
}
|
||||
|
||||
discovered, listUpdated, failed := 0, 0, 0
|
||||
results := []map[string]any{}
|
||||
newOrderIDs := make(map[string]struct{})
|
||||
if fetcher, ok := s.mtopClient().(mtop.SoldOrderFetcher); ok {
|
||||
for cid, cookieValue := range all {
|
||||
accountDiscovered, accountUpdated, accountNewIDs, discoveryErr := s.discoverSoldOrders(r.Context(), fetcher, cid, cookieValue)
|
||||
discovered += accountDiscovered
|
||||
listUpdated += accountUpdated
|
||||
for orderID := range accountNewIDs {
|
||||
newOrderIDs[orderID] = struct{}{}
|
||||
}
|
||||
result := map[string]any{
|
||||
"cookie_id": cid, "stage": "discover", "success": discoveryErr == nil,
|
||||
"discovered": accountDiscovered, "updated": accountUpdated,
|
||||
}
|
||||
if discoveryErr != nil {
|
||||
failed++
|
||||
result["error"] = discoveryErr.Error()
|
||||
}
|
||||
results = append(results, result)
|
||||
}
|
||||
} else {
|
||||
failed++
|
||||
results = append(results, map[string]any{"stage": "discover", "success": false, "error": "当前 MTop 客户端不支持订单列表发现"})
|
||||
}
|
||||
|
||||
ordersByCookie := map[string][]refreshTarget{}
|
||||
for cid := range all {
|
||||
for offset := 0; ; offset += 500 {
|
||||
@@ -196,7 +221,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
// 稳定状态无需反复抓取;但历史订单若缺少实付金额,仍需补全详情。
|
||||
if isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" {
|
||||
_, isNewOrder := newOrderIDs[row.OrderID]
|
||||
if !isNewOrder && isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" {
|
||||
continue
|
||||
}
|
||||
ordersByCookie[cid] = append(ordersByCookie[cid], refreshTarget{OrderID: row.OrderID, CurrentStatus: currentStatus})
|
||||
@@ -211,18 +237,39 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
for _, targets := range ordersByCookie {
|
||||
total += len(targets)
|
||||
}
|
||||
if s.Browser == nil {
|
||||
message := "订单列表同步完成"
|
||||
if discovered > 0 {
|
||||
message = fmt.Sprintf("订单列表同步完成,发现并导入 %d 个新订单", discovered)
|
||||
}
|
||||
if total > 0 {
|
||||
message += fmt.Sprintf(";浏览器自动化未启用,已跳过 %d 个订单的详情补全", total)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": failed == 0,
|
||||
"message": message,
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "detail_total": total,
|
||||
"total": total, "updated": 0, "no_change": 0, "failed": failed,
|
||||
},
|
||||
"results": results,
|
||||
})
|
||||
return
|
||||
}
|
||||
if total == 0 {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"message": "没有需要刷新的订单",
|
||||
"summary": map[string]int{"total": 0, "updated": 0, "no_change": 0, "failed": 0},
|
||||
"results": []any{},
|
||||
"success": failed == 0,
|
||||
"message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "detail_total": 0,
|
||||
"total": 0, "updated": 0, "no_change": 0, "failed": failed,
|
||||
},
|
||||
"results": results,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
updated, noChange, failed := 0, 0, 0
|
||||
results := []map[string]any{}
|
||||
updated, noChange := 0, 0
|
||||
for cid, targets := range ordersByCookie {
|
||||
cookieValue := all[cid]
|
||||
if cookieValue == "" {
|
||||
@@ -298,13 +345,90 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"message": "订单刷新完成",
|
||||
"summary": map[string]int{"total": total, "updated": updated, "no_change": noChange, "failed": failed},
|
||||
"success": failed == 0,
|
||||
"message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "detail_total": total,
|
||||
"total": total, "updated": updated, "no_change": noChange, "failed": failed,
|
||||
},
|
||||
"results": results,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, error) {
|
||||
discovered, updated := 0, 0
|
||||
newOrderIDs := make(map[string]struct{})
|
||||
for pageNumber := 1; pageNumber <= maxSoldOrderPages; pageNumber++ {
|
||||
page, err := fetcher.FetchSoldOrdersPage(ctx, cookies, pageNumber, 30)
|
||||
if err != nil {
|
||||
return discovered, updated, newOrderIDs, err
|
||||
}
|
||||
pageChanged := false
|
||||
for _, remote := range page.Items {
|
||||
if normalizedAmount, ok := db.NormalizeOrderAmount(remote.Amount); ok {
|
||||
remote.Amount = normalizedAmount
|
||||
}
|
||||
existing, getErr := s.Store.Orders.Get(ctx, remote.OrderID)
|
||||
isNew := errors.Is(getErr, db.ErrNotFound)
|
||||
if getErr != nil && !isNew {
|
||||
return discovered, updated, newOrderIDs, fmt.Errorf("读取订单 %s 失败: %w", remote.OrderID, getErr)
|
||||
}
|
||||
changed := isNew || soldOrderChanged(existing, remote)
|
||||
status := remote.OrderStatus
|
||||
if !isNew && status == "unknown" {
|
||||
status = ""
|
||||
}
|
||||
var isBargain *bool
|
||||
if remote.IsBargain {
|
||||
value := true
|
||||
isBargain = &value
|
||||
}
|
||||
if err := s.Store.Orders.Upsert(ctx, remote.OrderID, db.OrderUpsertOpts{
|
||||
ItemID: remote.ItemID, BuyerID: remote.BuyerID, CookieID: cookieID,
|
||||
OrderStatus: status, Quantity: remote.Quantity, Amount: remote.Amount,
|
||||
ReceiverName: remote.ReceiverName, ReceiverPhone: remote.ReceiverPhone,
|
||||
ReceiverAddr: remote.ReceiverAddr, ReceiverCity: remote.ReceiverCity,
|
||||
IsBargain: isBargain,
|
||||
}); err != nil {
|
||||
return discovered, updated, newOrderIDs, fmt.Errorf("保存订单 %s 失败: %w", remote.OrderID, err)
|
||||
}
|
||||
if isNew {
|
||||
discovered++
|
||||
newOrderIDs[remote.OrderID] = struct{}{}
|
||||
} else if changed {
|
||||
updated++
|
||||
}
|
||||
pageChanged = pageChanged || changed
|
||||
}
|
||||
if !page.NextPage || len(page.Items) == 0 {
|
||||
return discovered, updated, newOrderIDs, nil
|
||||
}
|
||||
// 卖家列表按新到旧排列。一整页都已存在且字段未变化时,更早页也无需重复扫描。
|
||||
if !pageChanged {
|
||||
return discovered, updated, newOrderIDs, nil
|
||||
}
|
||||
}
|
||||
return discovered, updated, newOrderIDs, fmt.Errorf("订单列表超过 %d 页,已停止继续同步", maxSoldOrderPages)
|
||||
}
|
||||
|
||||
func soldOrderChanged(existing *db.Order, remote mtop.SoldOrder) bool {
|
||||
if existing == nil {
|
||||
return true
|
||||
}
|
||||
statusChanged := remote.OrderStatus != "" && remote.OrderStatus != "unknown" &&
|
||||
db.NormalizeOrderStatus(existing.OrderStatus) != remote.OrderStatus
|
||||
return statusChanged ||
|
||||
(remote.ItemID != "" && existing.ItemID != remote.ItemID) ||
|
||||
(remote.BuyerID != "" && existing.BuyerID != remote.BuyerID) ||
|
||||
(remote.Quantity != "" && existing.Quantity != remote.Quantity) ||
|
||||
(remote.Amount != "" && existing.Amount != remote.Amount) ||
|
||||
(remote.ReceiverName != "" && existing.ReceiverName != remote.ReceiverName) ||
|
||||
(remote.ReceiverPhone != "" && existing.ReceiverPhone != remote.ReceiverPhone) ||
|
||||
(remote.ReceiverAddr != "" && existing.ReceiverAddr != remote.ReceiverAddr) ||
|
||||
(remote.ReceiverCity != "" && existing.ReceiverCity != remote.ReceiverCity) ||
|
||||
(remote.IsBargain && existing.IsBargain == 0)
|
||||
}
|
||||
|
||||
func chunkRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget {
|
||||
if size <= 0 {
|
||||
size = refreshOrderChunkSize
|
||||
|
||||
@@ -4,13 +4,14 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestRefreshOrdersNoBrowser 浏览器未启用时应 503。
|
||||
// TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。
|
||||
func TestRefreshOrdersNoBrowser(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
@@ -21,8 +22,38 @@ func TestRefreshOrdersNoBrowser(t *testing.T) {
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("无浏览器应 503,got %d body=%s", rec.Code, rec.Body.String())
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "订单列表同步完成") {
|
||||
t.Fatalf("无浏览器仍应同步列表,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` +
|
||||
`"commonData":{"orderId":"sold-new-1","itemId":"item-new","orderStatus":"待发货","inRefund":"false"},` +
|
||||
`"buyerInfoVO":{"buyerId":"buyer-1","name":"张三","phone":"13800000000","address":"上海市"},` +
|
||||
`"priceVO":{"totalPrice":"19.90","buyNum":"2"},` +
|
||||
`"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}`
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
|
||||
}))
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"discovered":1`) {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
order, err := store.Orders.Get(context.Background(), "sold-new-1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if order.CookieID != "acc1" || order.ItemID != "item-new" || order.OrderStatus != "pending_ship" ||
|
||||
order.Amount != "19.90" || order.Quantity != "2" || order.IsBargain != 1 || order.ReceiverName != "张三" {
|
||||
t.Fatalf("discovered order=%+v", order)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -122,6 +122,27 @@ func TestPreviewItemPublishBatchNoFile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewItemPublishBatchRequiresDefaultAccount(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
file, _ := mw.CreateFormFile("file", "products.csv")
|
||||
file.Write([]byte("标题,价格,图片\n商品A,12.50,https://example.com/a.png\n"))
|
||||
_ = mw.Close()
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "请选择默认发布账号") {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchBadDefaultCookie 默认账号不属于当前用户 403。
|
||||
func TestPreviewItemPublishBatchBadDefaultCookie(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"xianyu-go/internal/webui"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/qrlogin"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
type qrLoginService interface {
|
||||
@@ -63,6 +64,7 @@ type Server struct {
|
||||
PasswordLogin passwordLoginRunner
|
||||
notifier *notify.Notifier
|
||||
MTop mtop.Client
|
||||
CookieRenew xrenew.Service
|
||||
QRLogin qrLoginService
|
||||
Logger *slog.Logger
|
||||
WebDir string // 前端静态资源目录(含 index.html)
|
||||
@@ -110,6 +112,7 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure
|
||||
PasswordLogin: passwordLoginRunnerForBrowser(bm),
|
||||
notifier: notifier,
|
||||
MTop: mtop.NewClient(),
|
||||
CookieRenew: xrenew.Service{},
|
||||
QRLogin: qrMgr,
|
||||
Logger: logger,
|
||||
WebDir: webDir,
|
||||
|
||||
+76
-66
@@ -23,329 +23,339 @@ import{r as s}from"./react-vendor-DZnRGM0-.js";/**
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const m=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],L1=e("activity",m);/**
|
||||
*/const m=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],P1=e("activity",m);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],V1=e("arrow-right",u);/**
|
||||
*/const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],S1=e("arrow-right",u);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const w=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],P1=e("bell",w);/**
|
||||
*/const w=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],U1=e("bell",w);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const $=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],S1=e("bot",$);/**
|
||||
*/const $=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],E1=e("bot",$);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const N=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],U1=e("box",N);/**
|
||||
*/const N=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],B1=e("box",N);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],E1=e("check",f);/**
|
||||
*/const f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],D1=e("check",f);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const b=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],B1=e("chevron-down",b);/**
|
||||
*/const b=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],R1=e("chevron-down",b);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const C=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],D1=e("chevron-left",C);/**
|
||||
*/const q=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],T1=e("chevron-left",q);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const q=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],R1=e("chevron-right",q);/**
|
||||
*/const z=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Z1=e("chevron-right",z);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const z=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],T1=e("circle-alert",z);/**
|
||||
*/const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],F1=e("circle-alert",A);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Z1=e("circle-check",A);/**
|
||||
*/const C=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],I1=e("circle-check",C);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const j=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],I1=e("circle-dashed",j);/**
|
||||
*/const H=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],K1=e("circle-dashed",H);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const H=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K1=e("clock-3",H);/**
|
||||
*/const j=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],O1=e("clock-3",j);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const L=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],O1=e("clock",L);/**
|
||||
*/const L=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],W1=e("clock",L);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const V=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],W1=e("cloud-upload",V);/**
|
||||
*/const V=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],G1=e("cloud-upload",V);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const P=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],F1=e("code",P);/**
|
||||
*/const P=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q1=e("code",P);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const S=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],G1=e("copy",S);/**
|
||||
*/const S=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],J1=e("copy",S);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const U=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],Q1=e("credit-card",U);/**
|
||||
*/const U=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],X1=e("credit-card",U);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const E=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],J1=e("database",E);/**
|
||||
*/const E=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Y1=e("database",E);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const B=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],X1=e("dollar-sign",B);/**
|
||||
*/const B=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],e0=e("dollar-sign",B);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const D=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Y1=e("external-link",D);/**
|
||||
*/const D=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],a0=e("external-link",D);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const R=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],e0=e("eye-off",R);/**
|
||||
*/const R=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],t0=e("eye-off",R);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const T=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],a0=e("eye",T);/**
|
||||
*/const T=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],o0=e("eye",T);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Z=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],t0=e("file-down",Z);/**
|
||||
*/const Z=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],c0=e("file-down",Z);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const I=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],o0=e("file-text",I);/**
|
||||
*/const F=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],h0=e("file-text",F);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],c0=e("gift",K);/**
|
||||
*/const I=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],s0=e("funnel",I);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const O=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],h0=e("image",O);/**
|
||||
*/const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],n0=e("gift",K);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const W=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],s0=e("key",W);/**
|
||||
*/const O=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],d0=e("image",O);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const F=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],n0=e("layers",F);/**
|
||||
*/const W=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],y0=e("key",W);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const G=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],d0=e("layout-dashboard",G);/**
|
||||
*/const G=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],k0=e("layers",G);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Q=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],y0=e("link-2",Q);/**
|
||||
*/const Q=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],r0=e("layout-dashboard",Q);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const J=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],k0=e("list-plus",J);/**
|
||||
*/const J=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],i0=e("link-2",J);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const X=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],r0=e("loader-circle",X);/**
|
||||
*/const X=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],p0=e("list-plus",X);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Y=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],i0=e("lock-keyhole",Y);/**
|
||||
*/const Y=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],l0=e("loader-circle",Y);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const e1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],p0=e("lock",e1);/**
|
||||
*/const e1=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],_0=e("lock-keyhole",e1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const a1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],l0=e("log-out",a1);/**
|
||||
*/const a1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],M0=e("lock",a1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const t1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],_0=e("mail",t1);/**
|
||||
*/const t1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],v0=e("log-out",t1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const o1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],M0=e("message-circle",o1);/**
|
||||
*/const o1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],x0=e("mail",o1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const c1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],v0=e("package-check",c1);/**
|
||||
*/const c1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],g0=e("message-circle",c1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const h1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],x0=e("package-plus",h1);/**
|
||||
*/const h1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],m0=e("package-check",h1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const s1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],g0=e("package",s1);/**
|
||||
*/const s1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],u0=e("package-plus",s1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const n1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],m0=e("pen",n1);/**
|
||||
*/const n1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],w0=e("package",n1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const d1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],u0=e("plus",d1);/**
|
||||
*/const d1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],$0=e("pen",d1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const y1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],w0=e("power",y1);/**
|
||||
*/const y1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],N0=e("plus",y1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const k1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],$0=e("qr-code",k1);/**
|
||||
*/const k1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],f0=e("power",k1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const r1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],N0=e("refresh-cw",r1);/**
|
||||
*/const r1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],b0=e("qr-code",r1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const i1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],f0=e("save",i1);/**
|
||||
*/const i1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],q0=e("refresh-cw",i1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const p1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],b0=e("search",p1);/**
|
||||
*/const p1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],z0=e("save",p1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const l1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],C0=e("send",l1);/**
|
||||
*/const l1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],A0=e("search",l1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const _1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],q0=e("settings",_1);/**
|
||||
*/const _1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],C0=e("send",_1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const M1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],z0=e("shield-check",M1);/**
|
||||
*/const M1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],H0=e("settings",M1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const v1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],A0=e("shopping-bag",v1);/**
|
||||
*/const v1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],j0=e("shield-check",v1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const x1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],j0=e("shopping-cart",x1);/**
|
||||
*/const x1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],L0=e("shopping-bag",x1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const g1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],H0=e("sparkles",g1);/**
|
||||
*/const g1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],V0=e("shopping-cart",g1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const m1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],L0=e("square-pen",m1);/**
|
||||
*/const m1=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],P0=e("sliders-horizontal",m1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const u1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],V0=e("trash-2",u1);/**
|
||||
*/const u1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],S0=e("sparkles",u1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const w1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],P0=e("trending-up",w1);/**
|
||||
*/const w1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],U0=e("square-pen",w1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const $1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],S0=e("triangle-alert",$1);/**
|
||||
*/const $1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],E0=e("trash-2",$1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const N1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],U0=e("truck",N1);/**
|
||||
*/const N1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],B0=e("trending-up",N1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const f1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],E0=e("upload",f1);/**
|
||||
*/const f1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],D0=e("triangle-alert",f1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const b1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],B0=e("user-round",b1);/**
|
||||
*/const b1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],R0=e("truck",b1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const C1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],D0=e("user",C1);/**
|
||||
*/const q1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],T0=e("upload",q1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const q1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],R0=e("users",q1);/**
|
||||
*/const z1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Z0=e("user-round",z1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const z1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],T0=e("webhook",z1);/**
|
||||
*/const A1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],F0=e("user",A1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const A1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Z0=e("x",A1);/**
|
||||
*/const C1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],I0=e("users",C1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const j1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],I0=e("zap",j1);export{J1 as $,L1 as A,U1 as B,Q1 as C,X1 as D,Y1 as E,G1 as F,o0 as G,k0 as H,h0 as I,t0 as J,s0 as K,d0 as L,F1 as M,x0 as N,W1 as O,g0 as P,$0 as Q,N0 as R,A0 as S,P0 as T,R0 as U,Z1 as V,I1 as W,Z0 as X,y0 as Y,I0 as Z,V1 as _,P1 as a,B1 as a0,z0 as a1,i0 as a2,B0 as a3,M0 as a4,K1 as a5,c0 as a6,n0 as a7,C0 as a8,_0 as a9,T0 as aa,p0 as ab,q0 as b,H0 as c,l0 as d,T1 as e,j0 as f,v0 as g,S0 as h,r0 as i,D0 as j,E1 as k,S1 as l,O1 as m,m0 as n,w0 as o,V0 as p,e0 as q,a0 as r,f0 as s,u0 as t,U0 as u,b0 as v,L0 as w,D1 as x,R1 as y,E0 as z};
|
||||
*/const H1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],K0=e("webhook",H1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const j1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],O0=e("x",j1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const L1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],W0=e("zap",L1);export{i0 as $,P1 as A,B1 as B,X1 as C,e0 as D,a0 as E,P0 as F,J1 as G,h0 as H,d0 as I,p0 as J,y0 as K,r0 as L,c0 as M,Q1 as N,s0 as O,w0 as P,b0 as Q,q0 as R,L0 as S,B0 as T,I0 as U,u0 as V,G1 as W,O0 as X,I1 as Y,W0 as Z,K1 as _,U1 as a,S1 as a0,Y1 as a1,R1 as a2,j0 as a3,_0 as a4,Z0 as a5,g0 as a6,O1 as a7,n0 as a8,k0 as a9,C0 as aa,x0 as ab,K0 as ac,M0 as ad,H0 as b,S0 as c,v0 as d,F1 as e,V0 as f,m0 as g,D0 as h,l0 as i,F0 as j,D1 as k,E1 as l,W1 as m,$0 as n,f0 as o,E0 as p,t0 as q,o0 as r,z0 as s,N0 as t,R0 as u,A0 as v,U0 as w,T1 as x,Z1 as y,T0 as z};
|
||||
@@ -1,19 +0,0 @@
|
||||
import{j as e,r as n,b as ke,c as Qt,d as Kt}from"./react-vendor-DZnRGM0-.js";import{L as Yt,U as wt,S as kt,C as Fs,B as Ct,Z as Ts,a as is,b as zs,c as St,d as Xt,e as os,A as Xs,D as Zt,f as Zs,P as At,g as gs,E as It,T as Ht,h as ea,i as Le,Q as Ss,j as Os,k as We,l as rs,m as Hs,R as qe,n as Rt,o as sa,p as Ve,X as Ne,K as ta,q as ns,r as es,s as Je,t as Ge,u as et,v as aa,w as cs,x as la,y as ra,z as hs,F as na,G as st,I as tt,H as ia,J as oa,M as ca,N as As,O as ys,V as $t,W as da,Y as xa,_ as qs,$ as ma,a0 as ua,a1 as Ms,a2 as at,a3 as pa,a4 as _s,a5 as Lt,a6 as ha,a7 as ga,a8 as Us,a9 as Pt,aa as ba,ab as ya}from"./icons-vendor-BhUPp6x7.js";import{R as fs,B as fa,X as lt,Y as rt,T as Is,a as ja,C as Rs,A as Na,b as va,c as _a,P as nt,d as it,L as wa}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))d(u);new MutationObserver(u=>{for(const b of u)if(b.type==="childList")for(const k of b.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&d(k)}).observe(document,{childList:!0,subtree:!0});function l(u){const b={};return u.integrity&&(b.integrity=u.integrity),u.referrerPolicy&&(b.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?b.credentials="include":u.crossOrigin==="anonymous"?b.credentials="omit":b.credentials="same-origin",b}function d(u){if(u.ep)return;u.ep=!0;const b=l(u);fetch(u.href,b)}})();const ka=({activeTab:s,isAdmin:t=!1,onNavigate:l,onLogout:d})=>{const u=[{id:"dashboard",icon:Yt,label:"仪表盘"},{id:"accounts",icon:wt,label:"账号管理"},{id:"orders",icon:kt,label:"订单管理"},{id:"cards",icon:Fs,label:"卡密库存"},{id:"items",icon:Ct,label:"商品列表"},{id:"rules",icon:Ts,label:"自动化规则"},{id:"notifications",icon:is,label:"通知设置"},...t?[{id:"settings",icon:zs,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:u.map(b=>{const k=b.icon,O=s===b.id;return e.jsxs("button",{onClick:()=>l(b.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${O?"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 ${O?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:b.label}),O&&e.jsx(St,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},b.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:d,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(Xt,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Ca=3e4,Sa=10*6e4;let $s=!1;const Et=()=>{$s||typeof window>"u"||($s=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{$s=!1}))},Aa=s=>{if(!s)return"";const t=new URLSearchParams;for(const[d,u]of Object.entries(s))u!=null&&t.set(d,String(u));const l=t.toString();return l?`?${l}`:""},Cs=async(s,t,l={})=>{var R;const d=Aa(l.params),u=`${t}${d}`,b=Dt(l.signal,l.timeoutMs??Ca);let k;try{k=await fetch(u,{method:s,credentials:"include",signal:b.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(f){throw b.signal.aborted?new Error((R=l.signal)!=null&&R.aborted?"请求已取消":"请求超时,请稍后重试"):f}finally{b.cleanup()}const p=(k.headers.get("content-type")||"").includes("application/json");if(!k.ok){k.status===401&&!l.skipAuthLogout&&Et();const f=p?await k.json().catch(()=>{}):await k.text().catch(()=>{}),Q=typeof f=="string"?f:(f==null?void 0:f.detail)||(f==null?void 0:f.message)||(f==null?void 0:f.msg);throw new Error(Q||`请求失败: ${k.status}`)}return p?await k.json():await k.text()},ge=async(s,t,l)=>Cs("GET",s,{params:t,...l}),pe=async(s,t,l)=>Cs("POST",s,{body:t,...l}),Ee=async(s,t,lLine 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(zs,{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:v,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:i,children:"取消"}),e.jsxs("button",{onClick:ze,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:i,children:[i?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),i?"保存中...":"保存"]})]})})]})}),document.body)]})},Yl=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),Xl=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],gt=({status:s})=>{const t={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",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},Zl=()=>{const[s,t]=n.useState([]),[l,d]=n.useState([]),[u,b]=n.useState({}),[k,O]=n.useState("all"),[p,R]=n.useState(""),[f,Q]=n.useState(""),se=n.useRef(0),[U,J]=n.useState(1),[S,K]=n.useState(1),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState(!1),[Z,W]=n.useState(!1),[A,Y]=n.useState(null),[L,te]=n.useState(null),[T,h]=n.useState({}),[$,z]=n.useState(!1),[X,m]=n.useState(""),[_,N]=n.useState(!1),[y,P]=n.useState(null),[M,i]=n.useState(null),[E,w]=n.useState(null),[G,me]=n.useState(!1),[ie,H]=n.useState(null),[c,C]=n.useState(null),oe=async()=>{const x=++se.current;le(!0);try{const V=await Qa(void 0,k,U,20,f);if(x!==se.current)return;t(V.data),K(V.total_pages)}catch(V){console.error("加载订单失败:",V)}finally{x===se.current&&le(!1)}},be=(x,V)=>{if(V&&V.trim())return V;if(u[x])return u[x];const he=l.find(Ce=>{if(V&&Ce.item_title){const Be=V.toLowerCase(),Te=Ce.item_title.toLowerCase();return Te.includes(Be)||Be.includes(Te)}return!1});return he!=null&&he.item_title?he.item_title:"未知商品"},ye=x=>{const V={};x.forEach(he=>{he.item_id&&(V[he.item_id]=he.item_title||he.item_id)}),b(V)};n.useEffect(()=>{const x=window.setTimeout(()=>{J(1),Q(p.trim())},300);return()=>window.clearTimeout(x)},[p]),n.useEffect(()=>{oe()},[k,U,f]),n.useEffect(()=>{ds().then(x=>{d(x),ye(x)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const Se=async()=>{le(!0);try{const x=await Xa();await oe(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{le(!1)}},ve=x=>{m(x),P(null),z(!0)},fe=async x=>{var V;N(!0),P(null);try{const he=await Ha([X],x),Ce=(V=he==null?void 0:he.results)==null?void 0:V[0];Ce!=null&&Ce.success?(P({success:!0,message:Ce.message}),oe()):P({success:!1,message:(Ce==null?void 0:Ce.message)||"发货失败"})}catch(he){P({success:!1,message:(he==null?void 0:he.message)||"请求失败"})}finally{N(!1)}},De=x=>{Y(x),q(!0)},ue=x=>{te({...x}),D(!0)},Ae=async()=>{if(!(!L||!L.order_id))try{const x={};L.status!==void 0&&(x.order_status=L.status),L.buyer_id!==void 0&&(x.buyer_id=L.buyer_id),L.amount!==void 0&&(x.amount=L.amount),L.receiver_name!==void 0&&(x.receiver_name=L.receiver_name),L.receiver_phone!==void 0&&(x.receiver_phone=L.receiver_phone),L.receiver_address!==void 0&&(x.receiver_address=L.receiver_address),L.item_id!==void 0&&(x.item_id=L.item_id),L.quantity!==void 0&&(x.quantity=L.quantity),L.item_title!==void 0&&(x.item_title=L.item_title),await Ka(L.order_id,x),D(!1),te(null),oe()}catch(x){console.error("更新订单失败:",x),alert("更新失败,请重试")}},Re=async()=>{if(M){me(!0);try{const x=new FormData;x.append("file",
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(H=>H.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),G=new Blob(["\uFEFF"+w],{type:"text/csv;charset=utf-8"}),me=URL.createObjectURL(G),ie=document.createElement("a");ie.href=me,ie.download="卡密组批量导入模板.csv",document.body.appendChild(ie),ie.click(),ie.remove(),URL.revokeObjectURL(me)},y=async()=>{if(K){B(!0),ne(null);try{const i=await nl(K);if(ne(i),i.created>0){const E=await Ue();t(E)}}catch(i){ne({error:(i==null?void 0:i.message)||"上传失败"})}finally{B(!1)}}},P=async()=>{if(!(!D||!W.trim())){B(!0),L(null);try{const i=await il(D,W);L({added:i.added}),A("");const E=await Ue();t(E)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{B(!1)}}},M=()=>{var i;S("create"),de(null),ne(null),Z((i=_[0])!=null&&i.id?String(_[0].id):""),A(""),L(null),U(!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:M,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(hs,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>b(!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(Ge,{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 E="";return i.type==="data"&&i.data_content?E=`库存: ${i.data_content.split(`
|
||||
`).filter(G=>G.trim()).length} 条`:i.type==="text"&&i.text_content?E=i.text_content.substring(0,20)+(i.text_content.length>20?"...":""):i.type==="api"&&i.api_config?E=i.api_config.url:i.type==="image"&&i.image_url&&(E="图片链接"),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(te,{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(na,{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:E,children:E})}),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:()=>X(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:()=>T(i),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>$(i.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:e.jsx(Ve,{className:"w-5 h-5"})})]})})]},i.id)})})]})}),s.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(At,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),l&&k&&ke.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:()=>d(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Ne,{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=>R({...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=>R({...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:"批量数据"}),(k==null?void 0:k.type)==="api"&&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=>R({...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=>R({...p,api_mLine 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=>R({...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=>R({...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=>R({...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:()=>R({...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:()=>d(!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:h,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),u&&ke.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:()=>b(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Ne,{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:f.name,onChange:i=>Q({...f,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-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Fs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(st,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),f.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:f.content.split(`
|
||||
`).filter(i=>i.trim()).length})," 条"]})]}),f.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:f.api_method,onChange:i=>Q({...f,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:f.api_timeout,onChange:i=>Q({...f,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:f.api_headers,onChange:i=>Q({...f,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:f.api_params,onChange:i=>Q({...f,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:f.description,onChange:i=>Q({...f,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:f.delay_seconds,onChange:i=>Q({...f,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:()=>b(!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(Ge,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),se&&ke.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:()=>U(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Ne,{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:()=>S("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 ${J==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(ia,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>S("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 ${J==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(hs,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),J==="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;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:N,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-sm
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:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),Y&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",Y.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:()=>U(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),J==="create"?e.jsxs("button",{onClick:y,disabled:!K||q,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[q?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(hs,{className:"w-4 h-4"}),q?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:P,disabled:!D||!W.trim()||q||_.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[q?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),q?"处理中...":"追加卡密"]})]})]})}),document.body)]})},er=s=>s.find(t=>t.status==="running"||t.status==="canceling"),sr=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},tr=({onConfigureDelivery:s})=>{const[t,l]=n.useState([]),[d,u]=n.useState([]),[b,k]=n.useState([]),[O,p]=n.useState(""),[R,f]=n.useState(!1),[Q,se]=n.useState(!1),[U,J]=n.useState(!1),[S,K]=n.useState(!1),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState(!1),[Z,W]=n.useState("upload"),[A,Y]=n.useState(null),[L,te]=n.useState(null),[T,h]=n.useState(null),[$,z]=n.useState(null),[X,m]=n.useState(null),_=n.useRef(!1),[N,y]=n.useState(null),[P,M]=n.useState({}),[i,E]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[w,G]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[me,ie]=n.useState([]);n.useEffect(()=>{if(!ne||w.images.length===0){ie([]);return}const r=w.images.map((I,ce)=>({key:I.name+ce,url:URL.createObjectURL(I)}));return ie(r),()=>{r.forEach(I=>URL.revokeObjectURL(I.url))}},[ne,w.images]);const H=async()=>{const r=await ds();l(r)},c=async()=>{u(await ks())};n.useEffect(()=>{Promise.all([Vs(),ds(),ks(),xt(20)]).then(([r,I,ce,Qe])=>{k(r),l(I),u(ce);const ze=Qe.find(Ie=>["running","canceling"].includes(Ie.status))||Qe.find(Ie=>Ie.status!=="preview");m(ze||null)}).catch(r=>console.error("加载商品配置失败:",r))},[]),n.useEffect(()=>{if(!B||!($!=null&&$.id)||!["running","canceling"].includes($.status))return;const r=window.setInterval(async()=>{if(!_.current){_.current=!0;try{const I=await as($.id);z(I),m(I),["running","canceling"].includes(I.status)||(W("done"),await H(),await c())}catch(I){console.error("刷新批量铺货进度失败:",I)}finally{_.current=!1}}},3e3);return()=>{window.clearInterval(r)}},[B,$==null?void 0:$.id,$==null?void 0:$.status]);const C=async()=>{if(!O)return alert("请先选择账号");f(!0);try{const r=await ol(O);await H(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{f(!1)}},oe=r=>{y(r),M({...r}),K(!0)},be=async()=>{if(N)try{await bl(N.cookie_id,N.item_id,{item_title:P.item_title||"",item_description:P.item_description||"",item_category:P.item_category||"",item_price:P.item_price||"",item_detail:P.item_detail||N.item_detail||""}),await H(),await c(),K(!1),y(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},ye=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await cl(r.cookie_id,r.item_id),l(I=>I.filter(ce=>!(ce.cookie_id===r.cookie_id&&ce.item_id===r.item_id)))}catch(I){console.error("删除商品失败:",I),alert("删除失败,请重试")}},Se=async()=>{try{if(!i.cookie_id||!i.item_id){alert("请选择账号并填写商品ID");return}await dl(i.cookie_id,{item_id:i.item_id,item_title:i.item_title,item_price:i.item_price,item_detail:i.item_image?JSON.stringify({item_image:i.item_image}):""}),await H(),le(!1),E({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},ve=async()=>{if(!w.cookie_id)return alert("请选择发布账号");if(!w.title.trim())return alert("请填写商品标题");if(!w.price.trim())return alert("请填写商品价格");if(!w.quantity||Number(w.quantity)<=0)return alert("库存数量必须大于 0");if(w.images.length===0)return alert("至少上传 1 张商品图片");if(w.postage_mode==="fixed"&&!w.postage.trim())return alert("请填写一口价邮费");se(!0);try{const r=await xl(w);if(await H(),q(!1),G({cookie_id:O||"",title:"",description:""
Line truncated
|
||||
`),Qe=new Blob(["\uFEFF"+ce],{type:"text/csv;charset=utf-8"}),ze=URL.createObjectURL(Qe),Ie=document.createElement("a");Ie.href=ze,Ie.download="批量铺货模板.csv",document.body.appendChild(Ie),Ie.click(),Ie.remove(),URL.revokeObjectURL(ze)},V=()=>{E(r=>({...r,cookie_id:O||r.cookie_id})),le(!0)},he=()=>{G(r=>({...r,cookie_id:O||r.cookie_id})),q(!0)},Ce=r=>d.filter(I=>I.cookie_id===r.cookie_id&&I.item_id===r.item_id).length>0?d.filter(I=>I.cookie_id===r.cookie_id&&I.item_id===r.item_id):d.filter(I=>I.cookie_id===r.cookie_id&&!I.item_id),Be=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},Te=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:O,onChange:r=>p(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号以同步"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname},r.id))]}),e.jsxs("button",{onClick:C,disabled:R||!O,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(qe,{className:`w-4 h-4 ${R?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:V,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(Ge,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:he,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(As,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void fe(),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(ys,{className:"w-4 h-4"}),X&&["running","canceling"].includes(X.status)?"继续批量任务":"批量铺货"]}),X&&!["running","canceling"].includes(X.status)&&e.jsx("button",{onClick:()=>void De(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[t.map(r=>{const I=Ce(r),ce=I.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:()=>oe(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(cs,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>ye(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(Ve,{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(Ct,{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:sr(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 ${ce?"text-emerLine 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}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{Line truncated
|
||||
@@ -0,0 +1,19 @@
|
||||
import{j as e,r as n,b as Se,c as ra,d as na}from"./react-vendor-DZnRGM0-.js";import{L as ia,U as Pt,S as Tt,C as zs,B as Et,Z as Us,a as xs,b as Ys,c as Ft,d as oa,e as ms,A as rt,D as ca,f as nt,P as Dt,g as Ns,E as Mt,T as da,h as xa,i as Te,Q as Ps,j as ns,k as Ge,l as ds,m as it,R as qe,n as Ot,o as ma,p as Je,X as we,K as ua,q as rs,r as es,s as Ke,t as Qe,u as ot,v as qt,w as us,x as pa,y as ha,z as js,F as ga,G as ba,H as ct,I as dt,J as fa,M as ya,N as ja,O as Na,V as Ts,W as _s,Y as Bt,_ as va,$ as _a,a0 as Ws,a1 as wa,a2 as ka,a3 as Vs,a4 as xt,a5 as Ca,a6 as Ls,a7 as zt,a8 as Sa,a9 as La,aa as Zs,ab as Ut,ac as Aa,ad as Ia}from"./icons-vendor-RenKjhri.js";import{R as ws,B as $a,X as mt,Y as ut,T as Es,a as Ra,C as Fs,A as Pa,b as Ta,c as Ea,P as pt,d as ht,L as Fa}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const h of document.querySelectorAll('link[rel="modulepreload"]'))c(h);new MutationObserver(h=>{for(const f of h)if(f.type==="childList")for(const L of f.addedNodes)L.tagName==="LINK"&&L.rel==="modulepreload"&&c(L)}).observe(document,{childList:!0,subtree:!0});function l(h){const f={};return h.integrity&&(f.integrity=h.integrity),h.referrerPolicy&&(f.referrerPolicy=h.referrerPolicy),h.crossOrigin==="use-credentials"?f.credentials="include":h.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function c(h){if(h.ep)return;h.ep=!0;const f=l(h);fetch(h.href,f)}})();const Da=({className:s="w-full h-full text-white"})=>e.jsx("svg",{className:s,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),Gs=({sizeClass:s="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${s} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88Line 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:ve,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:z,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",disabled:z,children:[z?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),z?"保存中...":"保存"]})]})})]})}),document.body)]})},xr=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),mr=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],wt=({status:s})=>{const t={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",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},ur=()=>{const[s,t]=n.useState([]),[l,c]=n.useState([]),[h,f]=n.useState([]),[L,F]=n.useState({}),[g,I]=n.useState("all"),[j,G]=n.useState(""),[Y,X]=n.useState(""),[de,C]=n.useState(""),M=n.useRef(0),[oe,ee]=n.useState(1),[xe,O]=n.useState(1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState(!1),[ue,Q]=n.useState(!1),[A,b]=n.useState(null),[v,B]=n.useState(null),[R,K]=n.useState({}),[H,m]=n.useState(!1),[p,y]=n.useState(""),[S,U]=n.useState(!1),[se,z]=n.useState(null),[re,E]=n.useState(null),[i,q]=n.useState(null),[d,_]=n.useState(!1),[te,Z]=n.useState(null),[pe,Ne]=n.useState(null),ce=async()=>{const x=++M.current;D(!0);try{const P=await cl(j||void 0,g,oe,20,de);if(x!==M.current)return;t(P.data),O(P.total_pages)}catch(P){console.error("加载订单失败:",P)}finally{x===M.current&&D(!1)}},_e=(x,P,me)=>{if(me&&me.trim())return me;if(L[`${x}:${P}`])return L[`${x}:${P}`];const fe=l.find(ze=>{if(me&&ze.item_title){const r=me.toLowerCase(),a=ze.item_title.toLowerCase();return a.includes(r)||r.includes(a)}return!1});return fe!=null&&fe.item_title?fe.item_title:"未知商品"},Re=x=>{const P={};x.forEach(me=>{me.item_id&&(P[`${me.cookie_id}:${me.item_id}`]=me.item_title||me.item_id)}),F(P)};n.useEffect(()=>{const x=window.setTimeout(()=>{ee(1),C(Y.trim())},300);return()=>window.clearTimeout(x)},[Y]),n.useEffect(()=>{ce()},[j,g,oe,de]),n.useEffect(()=>{Promise.all([Rs(),ps()]).then(([x,P])=>{f(x),c(P),Re(P)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const ye=n.useMemo(()=>new Map(h.map(x=>[x.id,x])),[h]),Ae=x=>{const P=ye.get(x),me=(P==null?void 0:P.remark)||(P==null?void 0:P.nickname);return me?`${me} · ${x.slice(0,6)}`:`账号 ${x.slice(0,8)}`},Le=x=>{const P=ye.get(x);return(P==null?void 0:P.remark)||(P==null?void 0:P.nickname)||"未命名账号"},Be=async()=>{D(!0);try{const x=await ml(j||void 0,g);await ce(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{D(!1)}},Ie=x=>{y(x),z(null),m(!0)},Me=async x=>{var P;U(!0),z(null);try{const me=await pl([p],x),fe=(P=me==null?void 0:me.results)==null?void 0:P[0];fe!=null&&fe.success?(z({success:!0,message:fe.message}),ce()):z({success:!1,message:(fe==null?void 0:fe.message)||"发货失败"})}catch(me){z({success:!1,message:(me==null?void 0:me.message)||"请求失败"})}finally{U(!1)}},We=x=>{b(x),$(!0)},Ye=x=>{B({...x}),J(!0)},$e=async()=>{if(!(!v||!v.order_id))try{const x={};v.status!==void 0&&(x.order_status=v.status),v.buyer_id!==void 0&&(x.buyer_id=v.buyer_id),v.amount!==void 0&&(x.amount=v.amount),v.receiver_name!==void 0&&(x.receiver_name=v.receiver_name),v.receiver_phone!==void 0&&(x
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(pe=>pe.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),_=new Blob(["\uFEFF"+d],{type:"text/csv;charset=utf-8"}),te=URL.createObjectURL(_),Z=document.createElement("a");Z.href=te,Z.download="卡密组批量导入模板.csv",document.body.appendChild(Z),Z.click(),Z.remove(),URL.revokeObjectURL(te)},z=async()=>{if(M){le(!0),xe(null);try{const i=await Nl(M);if(xe(i),i.created>0){const q=await Ve();t(q)}}catch(i){xe({error:(i==null?void 0:i.message)||"上传失败"})}finally{le(!1)}}},re=async()=>{if(!(!D||!$.trim())){le(!0),ue(null);try{const i=await vl(D,$);ue({added:i.added}),T("");const q=await Ve();t(q)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{le(!1)}}},E=()=>{var i;C("create"),oe(null),xe(null),N((i=S[0])!=null&&i.id?String(S[0].id):""),T(""),ue(null),X(!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:E,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(js,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>f(!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(Qe,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ga,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:Q,onChange:i=>A(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(qt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:b,onChange:i=>v(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",U.length," / ",s.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed 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:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:U.map(i=>{let q="";return i.type==="data"&&i.data_content?q=`库存: ${i.data_content.split(`
|
||||
`).filter(_=>_.trim()).length} 条`:i.type==="text"&&i.text_content?q=i.text_content:i.type==="api"&&i.api_config?q=i.api_config.url:i.type==="image"&&i.image_url&&(q="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(B,{type:i.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:i.name,children:i.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>y(i.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:i.id}),e.jsx(ba,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] 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-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:q,children:q})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>p(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-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>R(i),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>H(i.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},i.id)})})]})}),U.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Dt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:s.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&L&&Se.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:()=>c(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(we,{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:g.name||"",onChange:i=>I({...g,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:g.type||"text",onChange:i=>I({...g,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:"批量数据"}),(L==null?void 0:L.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.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:g.api_url||"",onChange:i=>I({...g,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("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:g.data_content?g.data_content.split(`
|
||||
`).filter(i=>i.trim()).length:0})," 条"]})]})]}),g.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:g.image_url||"",onChange:i=>I({...g,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 地址"})]}),g.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:g.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:g.delay_seconds||0,onChange:i=>I({...g,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:g.description||"",onChange:i=>I({...g,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:()=>I({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.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 ${g.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:()=>c(!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(Ke,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),h&&Se.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:()=>f(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(we,{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:j.name,onChange:i=>G({...j,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-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(zs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ct,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:j.content.split(`
|
||||
`).filter(i=>i.trim()).length})," 条"]})]}),j.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:j.api_method,onChange:i=>G({...j,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:j.api_timeout,onChange:i=>G({...j,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:j.api_headers,onChange:i=>G({...j,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:j.api_params,onChange:i=>G({...j,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:j.description,onChange:i=>G({...j,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:j.delay_seconds,onChange:i=>G({...j,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:()=>f(!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:m,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Y&&Se.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:()=>X(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(we,{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:()=>C("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 ${de==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(fa,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>C("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 ${de==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(js,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),de==="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;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:se,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:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),J&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",J.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:()=>X(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),de==="create"?e.jsxs("button",{onClick:z,disabled:!M||O,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[O?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(js,{className:"w-4 h-4"}),O?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:re,disabled:!D||!$.trim()||O||S.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[O?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Qe,{className:"w-4 h-4"}),O?"处理中...":"追加卡密"]})]})]})}),document.body)]})},gr=s=>s.find(t=>t.status==="running"||t.status==="canceling"),br=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},fr=({onConfigureDelivery:s})=>{const[t,l]=n.useState([]),[c,h]=n.useState([]),[f,L]=n.useState([]),[F,g]=n.useState(""),[I,j]=n.useState(""),[G,Y]=n.useState(!1),[X,de]=n.useState(!1),[C,M]=n.useState(!1),[oe,ee]=n.useState(!1),[xe,O]=n.useState(!1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState("upload"),[ue,Q]=n.useState(null),[A,b]=n.useState(null),[v,B]=n.useState(null),[R,K]=n.useState(null),[H,m]=n.useState(null),p=n.useRef(!1),[y,S]=n.useState(null),[U,se]=n.useState({}),[z,re]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[E,i]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[q,d]=n.useState([]);n.useEffect(()=>{if(!le||E.images.length===0){d([]);return}const r=E.images.map((a,u)=>({key:a.name+u,url:URL.createObjectURL(a)}));return d(r),()=>{r.forEach(a=>URL.revokeObjectURL(a.url))}},[le,E.images]);const _=async()=>{const r=await ps();l(r)},te=async()=>{h(await Is())};n.useEffect(()=>{Promise.all([Rs(),ps(),Is(),yt(20)]).then(([r,a,u,w])=>{L(r),l(a),h(u);const W=w.find(ae=>["running","canceling"].includes(ae.status))||w.find(ae=>ae.status!=="preview");m(W||null)}).catch(r=>console.error("加载商品配置失败:",r))},[]),n.useEffect(()=>{if(!N||!(R!=null&&R.id)||!["running","canceling"].includes(R.status))return;const r=window.setInterval(async()=>{if(!p.current){p.current=!0;try{const a=await os(R.id);K(a),m(a),["running","canceling"].includes(a.status)||(J("done"),await _(),await te())}catch(a){console.error("刷新批量铺货进度失败:",a)}finally{p.current=!1}}},3e3);return()=>{window.clearInterval(r)}},[N,R==null?void 0:R.id,R==null?void 0:R.status]);const Z=async()=>{if(!F)return alert("请先选择账号");Y(!0);try{const r=await _l(F);await _(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{Y(!1)}},pe=r=>{S(r),se({...r}),ee(!0)},Ne=async()=>{if(y)try{await Rl(y.cookie_id,y.item_id,{item_title:U.item_title||"",item_description:U.item_description||"",item_category:U.item_category||"",item_price:U.item_price||"",item_detail:U.item_detail||y.item_detail||""}),await _(),await te(),ee(!1),S(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},ce=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await wl(r.cookie_id,r.item_id),l(a=>a.filter(u=>!(u.cookie_id===r.cookie_id&&u.item_id===r.item_id)))}catch(a){console.error("删除商品失败:",a),alert("删除失败,请重试")}},_e=async()=>{try{if(!z.cookie_id||!z.item_id){alert("请选择账号并填写商品ID");return}await kl(z.cookie_id,{item_id:z.item_id,item_title:z.item_title,item_price:z.item_price,item_detail:z.item_image?JSON.stringify({item_image:z.item_image}):""}),await _(),O(!1),re({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},Re=async()=>{if(!E.cookie_id)return alert("请选择发布账号");if(!E.title.trim())return alert("请填写商品标题");if(!E.price.trim())return alert("请填写商品价格");if(!E.quantity||Number(E.quantity)<=0)return alert("库存数量必须大于 0");if(E.images.length===0)return alert("至少上传 1 张商品图片");if(E.postage_mode==="fixed"&&!E.postage.trim())return alert("请填写一口价邮费");de(!0);try{const r=await Cl(E);if(await _(),D(!1),i({cookie_id:F||"",title:"
Line truncated
|
||||
`),w=new Blob(["\uFEFF"+u],{type:"text/csv;charset=utf-8"}),W=URL.createObjectURL(w),ae=document.createElement("a");ae.href=W,ae.download="批量铺货模板.csv",document.body.appendChild(ae),ae.click(),ae.remove(),URL.revokeObjectURL(W)},ss=()=>{re(r=>({...r,cookie_id:F||r.cookie_id})),O(!0)},Ze=()=>{i(r=>({...r,cookie_id:F||r.cookie_id})),D(!0)},Xe=r=>c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id).length>0?c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id):c.filter(a=>a.cookie_id===r.cookie_id&&!a.item_id),He=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},x=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"}},P=n.useMemo(()=>new Map(f.map(r=>[r.id,r])),[f]),me=n.useMemo(()=>I?t.filter(r=>r.cookie_id===I):t,[I,t]),fe=r=>{const a=P.get(r),u=(a==null?void 0:a.remark)||(a==null?void 0:a.nickname);return u?`${u} · ${r.slice(0,6)}`:`账号 ${r.slice(0,8)}`},ze=r=>{const a=P.get(r);return(a==null?void 0:a.remark)||(a==null?void 0:a.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",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 flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Na,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:r=>j(r.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ns,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:F,onChange:r=>g(r.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]})]}),e.jsxs("button",{onClick:Z,disabled:G||!F,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(qe,{className:`w-4 h-4 ${G?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ss,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(Qe,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ze,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(Ts,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void ye(),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(_s,{className:"w-4 h-4"}),H&&["running","canceling"].includes(H.status)?"继续批量任务":"批量铺货"]}),H&&!["running","canceling"].includes(H.status)&&e.jsx("button",{onClick:()=>void Ae(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[me.map(r=>{const a=Xe(r),u=a.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-
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}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-inset-1{top:-.25rem;right:-.25rem;bottom:-.25remLine 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-2Xnmtmdh.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-DWScSBc3.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-DZnRGM0-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BhUPp6x7.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-RenKjhri.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-D0gOrWMZ.css">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-hVsGsb1z.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -2,8 +2,12 @@ package cookierefresh
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -77,6 +81,185 @@ func MergeSetCookies(original string, setCookies []string) string {
|
||||
return MarshalCookieString(m)
|
||||
}
|
||||
|
||||
// SnapshotFromCookieString 为只有扁平 Cookie 的历史账号建立兼容快照。浏览器刷新后
|
||||
// 应使用真实快照覆盖它,避免长期依赖推断出的 Domain/Path。
|
||||
func SnapshotFromCookieString(cookieString, domain string) []BrowserCookie {
|
||||
domain = strings.TrimSpace(domain)
|
||||
if domain == "" {
|
||||
domain = ".goofish.com"
|
||||
}
|
||||
out := make([]BrowserCookie, 0)
|
||||
for name, value := range ParseCookieString(cookieString) {
|
||||
out = append(out, BrowserCookie{Name: name, Value: value, Domain: domain, Path: "/", Secure: true})
|
||||
}
|
||||
return NormalizeSnapshot(out)
|
||||
}
|
||||
|
||||
// ReconcileSnapshotWithCookieString 在调用方暂时只能获得扁平 Cookie 结果时保留
|
||||
// 已知属性,并同步值与删除项。新增字段使用 .goofish.com 根路径作为兼容作用域。
|
||||
func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString string) []BrowserCookie {
|
||||
values := ParseCookieString(cookieString)
|
||||
seen := make(map[string]struct{})
|
||||
out := make([]BrowserCookie, 0, len(snapshot)+len(values))
|
||||
for _, cookie := range NormalizeSnapshot(snapshot) {
|
||||
value, exists := values[cookie.Name]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
cookie.Value = value
|
||||
out = append(out, cookie)
|
||||
seen[cookie.Name] = struct{}{}
|
||||
}
|
||||
for name, value := range values {
|
||||
if _, exists := seen[name]; exists {
|
||||
continue
|
||||
}
|
||||
out = append(out, BrowserCookie{Name: name, Value: value, Domain: ".goofish.com", Path: "/", Secure: true})
|
||||
}
|
||||
return NormalizeSnapshot(out)
|
||||
}
|
||||
|
||||
// CookieHeaderForURL 按浏览器 Domain/Path/Secure/Expires 规则生成指定 URL 的
|
||||
// Cookie header,并保留不同路径下的同名 Cookie。
|
||||
func CookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time) string {
|
||||
target, err := url.Parse(rawURL)
|
||||
if err != nil || target.Hostname() == "" {
|
||||
return ""
|
||||
}
|
||||
type matchedCookie struct {
|
||||
cookie BrowserCookie
|
||||
index int
|
||||
}
|
||||
matched := make([]matchedCookie, 0, len(snapshot))
|
||||
for index, cookie := range NormalizeSnapshot(snapshot) {
|
||||
if cookie.Expires > 0 && cookie.Expires <= float64(now.Unix()) {
|
||||
continue
|
||||
}
|
||||
if cookie.Secure && target.Scheme != "https" && target.Scheme != "wss" {
|
||||
continue
|
||||
}
|
||||
if !cookieDomainMatches(target.Hostname(), cookie.Domain) || !cookiePathMatches(target.EscapedPath(), cookie.Path) {
|
||||
continue
|
||||
}
|
||||
matched = append(matched, matchedCookie{cookie: cookie, index: index})
|
||||
}
|
||||
sort.SliceStable(matched, func(i, j int) bool {
|
||||
if len(matched[i].cookie.Path) != len(matched[j].cookie.Path) {
|
||||
return len(matched[i].cookie.Path) > len(matched[j].cookie.Path)
|
||||
}
|
||||
return matched[i].index < matched[j].index
|
||||
})
|
||||
parts := make([]string, 0, len(matched))
|
||||
for _, item := range matched {
|
||||
parts = append(parts, item.cookie.Name+"="+item.cookie.Value)
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// ApplySetCookies 把某次请求响应的 Set-Cookie 应用到完整快照。删除操作只删除
|
||||
// 相同 name/domain/path 的 Cookie,不会误删其他作用域下的同名项。
|
||||
func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []string, now time.Time) []BrowserCookie {
|
||||
target, err := url.Parse(requestURL)
|
||||
if err != nil || target.Hostname() == "" {
|
||||
return NormalizeSnapshot(snapshot)
|
||||
}
|
||||
state := make(map[string]BrowserCookie)
|
||||
for _, cookie := range NormalizeSnapshot(snapshot) {
|
||||
state[snapshotKey(cookie)] = cookie
|
||||
}
|
||||
for _, raw := range setCookies {
|
||||
parsed, err := http.ParseSetCookie(raw)
|
||||
if err != nil || strings.TrimSpace(parsed.Name) == "" {
|
||||
continue
|
||||
}
|
||||
domain := strings.ToLower(strings.TrimSpace(parsed.Domain))
|
||||
if domain == "" {
|
||||
domain = strings.ToLower(target.Hostname())
|
||||
} else if !strings.HasPrefix(domain, ".") {
|
||||
domain = "." + domain
|
||||
}
|
||||
cookiePath := parsed.Path
|
||||
if cookiePath == "" {
|
||||
cookiePath = defaultCookiePath(target.Path)
|
||||
}
|
||||
cookie := BrowserCookie{
|
||||
Name: parsed.Name, Value: parsed.Value, Domain: domain, Path: cookiePath,
|
||||
HTTPOnly: parsed.HttpOnly, Secure: parsed.Secure, SameSite: sameSiteLabel(parsed.SameSite),
|
||||
}
|
||||
if !parsed.Expires.IsZero() {
|
||||
cookie.Expires = float64(parsed.Expires.Unix())
|
||||
}
|
||||
key := snapshotKey(cookie)
|
||||
if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(now)) {
|
||||
delete(state, key)
|
||||
continue
|
||||
}
|
||||
state[key] = cookie
|
||||
}
|
||||
out := make([]BrowserCookie, 0, len(state))
|
||||
for _, cookie := range state {
|
||||
out = append(out, cookie)
|
||||
}
|
||||
return NormalizeSnapshot(out)
|
||||
}
|
||||
|
||||
func snapshotKey(cookie BrowserCookie) string {
|
||||
return cookie.Name + "\x00" + strings.ToLower(cookie.Domain) + "\x00" + cookie.Path
|
||||
}
|
||||
|
||||
func cookieDomainMatches(host, domain string) bool {
|
||||
host = strings.ToLower(strings.TrimSpace(host))
|
||||
domain = strings.ToLower(strings.TrimSpace(domain))
|
||||
if domain == "" {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(domain, ".") {
|
||||
base := strings.TrimPrefix(domain, ".")
|
||||
return host == base || strings.HasSuffix(host, "."+base)
|
||||
}
|
||||
return host == domain
|
||||
}
|
||||
|
||||
func cookiePathMatches(requestPath, cookiePath string) bool {
|
||||
if requestPath == "" {
|
||||
requestPath = "/"
|
||||
}
|
||||
if cookiePath == "" {
|
||||
cookiePath = "/"
|
||||
}
|
||||
if requestPath == cookiePath {
|
||||
return true
|
||||
}
|
||||
if !strings.HasPrefix(requestPath, cookiePath) {
|
||||
return false
|
||||
}
|
||||
return strings.HasSuffix(cookiePath, "/") || (len(requestPath) > len(cookiePath) && requestPath[len(cookiePath)] == '/')
|
||||
}
|
||||
|
||||
func defaultCookiePath(requestPath string) string {
|
||||
if requestPath == "" || requestPath[0] != '/' || requestPath == "/" {
|
||||
return "/"
|
||||
}
|
||||
dir := path.Dir(requestPath)
|
||||
if dir == "." || dir == "/" {
|
||||
return "/"
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func sameSiteLabel(value http.SameSite) string {
|
||||
switch value {
|
||||
case http.SameSiteStrictMode:
|
||||
return "Strict"
|
||||
case http.SameSiteLaxMode:
|
||||
return "Lax"
|
||||
case http.SameSiteNoneMode:
|
||||
return "None"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// ChangedCookieNames 返回两个 Cookie 字符串之间发生变化的字段名。
|
||||
func ChangedCookieNames(before, after string) []string {
|
||||
a := ParseCookieString(before)
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package cookierefresh
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMetadataSnapshotKeyCompatibility(t *testing.T) {
|
||||
oldMeta := `{"cookie_refresh_snapshot":[{"name":"a","value":"1","domain":".goofish.com","path":"/"}]}`
|
||||
@@ -17,6 +21,43 @@ func TestMetadataSnapshotKeyCompatibility(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookieHeaderForURLScopesDomainPathAndSecure(t *testing.T) {
|
||||
now := time.Unix(1_800_000_000, 0)
|
||||
snapshot := []BrowserCookie{
|
||||
{Name: "root", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "passport", Value: "2", Domain: "passport.goofish.com", Path: "/newlogin", Secure: true},
|
||||
{Name: "other", Value: "3", Domain: "h5api.m.goofish.com", Path: "/", Secure: true},
|
||||
{Name: "expired", Value: "4", Domain: ".goofish.com", Path: "/", Expires: float64(now.Add(-time.Hour).Unix())},
|
||||
}
|
||||
got := CookieHeaderForURL(snapshot, "https://passport.goofish.com/newlogin/silentHasLogin.do", now)
|
||||
if got != "passport=2; root=1" {
|
||||
t.Fatalf("CookieHeaderForURL=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySetCookiesPreservesAttributesAndDeletesExactScope(t *testing.T) {
|
||||
now := time.Unix(1_800_000_000, 0)
|
||||
snapshot := []BrowserCookie{
|
||||
{Name: "sid", Value: "root", Domain: ".goofish.com", Path: "/"},
|
||||
{Name: "sid", Value: "login", Domain: ".goofish.com", Path: "/newlogin"},
|
||||
}
|
||||
updated := ApplySetCookies(snapshot, "https://passport.goofish.com/newlogin/silentHasLogin.do", []string{
|
||||
"sid=; Domain=.goofish.com; Path=/newlogin; Max-Age=0",
|
||||
"fresh=ok; Domain=.goofish.com; Path=/; Secure; HttpOnly; SameSite=None",
|
||||
}, now)
|
||||
if got := CookieHeaderForURL(updated, "https://www.goofish.com/", now); !strings.Contains(got, "sid=root") || !strings.Contains(got, "fresh=ok") {
|
||||
t.Fatalf("updated header=%q snapshot=%+v", got, updated)
|
||||
}
|
||||
for _, cookie := range updated {
|
||||
if cookie.Name == "sid" && cookie.Path == "/newlogin" {
|
||||
t.Fatalf("精确作用域删除失败: %+v", updated)
|
||||
}
|
||||
if cookie.Name == "fresh" && (!cookie.Secure || !cookie.HTTPOnly || cookie.SameSite != "None") {
|
||||
t.Fatalf("Cookie 属性未保留: %+v", cookie)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangedSnapshotLabels(t *testing.T) {
|
||||
before := []BrowserCookie{{Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"}}
|
||||
after := []BrowserCookie{{Name: "a", Value: "2", Domain: ".goofish.com", Path: "/"}}
|
||||
|
||||
@@ -35,6 +35,12 @@ const UserPageNavAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.user.page.n
|
||||
// ItemListAPI 是卖家商品列表端点。
|
||||
const ItemListAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.xyh.item.list/1.0/"
|
||||
|
||||
// SoldOrdersAPI 是闲鱼卖家工作台的已售订单列表端点。
|
||||
const SoldOrdersAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.trade.merchant.sold.get/1.0/"
|
||||
|
||||
// ItemDetailAPI 是闲鱼 PC 商品详情端点。
|
||||
const ItemDetailAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.pc.detail/1.0/"
|
||||
|
||||
const (
|
||||
MTopRetryGap = time.Second
|
||||
ItemPageGap = time.Second
|
||||
@@ -59,6 +65,8 @@ type ClientImpl struct {
|
||||
TokenURL string
|
||||
ConsignURL string
|
||||
OrderDetailURL string
|
||||
SoldOrdersURL string
|
||||
ItemDetailURL string
|
||||
LoginUserURL string
|
||||
TokenExecutor TokenRequestExecutor
|
||||
}
|
||||
@@ -151,6 +159,7 @@ type ItemListItem struct {
|
||||
ItemDetail string
|
||||
AuctionType string
|
||||
ItemStatus int
|
||||
IsMultiSpec bool
|
||||
}
|
||||
|
||||
func hasMTopSuccess(ret []string) bool {
|
||||
@@ -301,19 +310,16 @@ func mergeSetCookie(orig string, current map[string]string, resp *http.Response)
|
||||
}
|
||||
changed := false
|
||||
for _, sc := range setCookies {
|
||||
// Set-Cookie: name=value; Path=/; ...
|
||||
pair := sc
|
||||
if i := strings.Index(pair, ";"); i >= 0 {
|
||||
pair = pair[:i]
|
||||
parsed, err := http.ParseSetCookie(sc)
|
||||
if err != nil || strings.TrimSpace(parsed.Name) == "" {
|
||||
continue
|
||||
}
|
||||
if eq := strings.Index(pair, "="); eq >= 0 {
|
||||
name := strings.TrimSpace(pair[:eq])
|
||||
val := strings.TrimSpace(pair[eq+1:])
|
||||
if name != "" {
|
||||
current[name] = val
|
||||
changed = true
|
||||
}
|
||||
if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) {
|
||||
delete(current, parsed.Name)
|
||||
} else {
|
||||
current[parsed.Name] = parsed.Value
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return orig
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
// Package mtop: 商品详情域 — 补充商品列表未返回的多规格信息。
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// ItemDetailFetcher 是商品同步使用的可选详情能力。
|
||||
type ItemDetailFetcher interface {
|
||||
DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error)
|
||||
}
|
||||
|
||||
var _ ItemDetailFetcher = (*ClientImpl)(nil)
|
||||
|
||||
// DetectItemMultiSpec 查询商品详情并识别多规格结构。该调用不刷新 token,
|
||||
// 也不合并或持久化响应 Cookie。
|
||||
func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error) {
|
||||
itemID = strings.TrimSpace(itemID)
|
||||
if itemID == "" {
|
||||
return false, fmt.Errorf("item_id 不能为空")
|
||||
}
|
||||
token := protocol.SignToken(cookies)
|
||||
if token == "" {
|
||||
return false, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取商品详情")
|
||||
}
|
||||
dataVal := `{"itemId":` + strconv.Quote(itemID) + `}`
|
||||
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
sign := protocol.GenerateSign(timestamp, token, dataVal)
|
||||
endpoint := c.ItemDetailURL
|
||||
if endpoint == "" {
|
||||
endpoint = ItemDetailAPI
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildItemDetailQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
setCommonHeaders(req, cookies)
|
||||
req.Header.Set("Origin", "https://www.goofish.com")
|
||||
req.Header.Set("Referer", "https://www.goofish.com/item?id="+url.QueryEscape(itemID))
|
||||
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("商品详情请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := readMTopBody(resp)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var decoded struct {
|
||||
Ret []string `json:"ret"`
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||
return false, fmt.Errorf("解析商品详情响应失败: %w (body=%s)", err, truncate(string(raw), 300))
|
||||
}
|
||||
if !hasMTopSuccess(decoded.Ret) {
|
||||
return false, fmt.Errorf("商品详情接口返回非成功: ret=%v", decoded.Ret)
|
||||
}
|
||||
return detectItemMultiSpec(decoded.Data), nil
|
||||
}
|
||||
|
||||
func buildItemDetailQuery(timestamp, sign string) string {
|
||||
values := url.Values{
|
||||
"jsv": {"2.7.2"},
|
||||
"appKey": {protocol.SignAppKey},
|
||||
"t": {timestamp},
|
||||
"sign": {sign},
|
||||
"v": {"1.0"},
|
||||
"type": {"originaljson"},
|
||||
"accountSite": {"xianyu"},
|
||||
"dataType": {"json"},
|
||||
"timeout": {"20000"},
|
||||
"api": {"mtop.taobao.idle.pc.detail"},
|
||||
"sessionOption": {"AutoLoginOnly"},
|
||||
"spm_cnt": {"a21ybx.item.0.0"},
|
||||
}
|
||||
return values.Encode()
|
||||
}
|
||||
|
||||
func detectItemMultiSpec(value any) bool {
|
||||
return detectMultiSpecValue(value, false, 0)
|
||||
}
|
||||
|
||||
func detectMultiSpecValue(value any, skuContext bool, depth int) bool {
|
||||
if depth > 16 {
|
||||
return false
|
||||
}
|
||||
switch typed := value.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range typed {
|
||||
normalized := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(key))
|
||||
switch normalized {
|
||||
case "multisku", "ismultisku", "ismultispec", "multiplesku":
|
||||
if mtopBool(child) {
|
||||
return true
|
||||
}
|
||||
case "skulist", "skus":
|
||||
if list, ok := child.([]any); ok && len(list) > 1 {
|
||||
return true
|
||||
}
|
||||
case "skuprops", "skuproperties", "specprops", "specifications":
|
||||
if list, ok := child.([]any); ok && len(list) > 0 {
|
||||
return true
|
||||
}
|
||||
case "props", "properties":
|
||||
if skuContext {
|
||||
if list, ok := child.([]any); ok && len(list) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
nextSKUContext := skuContext || normalized == "skudo" || normalized == "skubase" || normalized == "skumodel"
|
||||
if detectMultiSpecValue(child, nextSKUContext, depth+1) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range typed {
|
||||
if detectMultiSpecValue(child, skuContext, depth+1) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDetectItemMultiSpec(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("api") != "mtop.taobao.idle.pc.detail" {
|
||||
t.Errorf("query=%s", r.URL.RawQuery)
|
||||
}
|
||||
rawBody, _ := io.ReadAll(r.Body)
|
||||
form, _ := url.ParseQuery(string(rawBody))
|
||||
if form.Get("data") != `{"itemId":"item-1"}` {
|
||||
t.Errorf("data=%q", form.Get("data"))
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"ret":["SUCCESS::调用成功"],"data":{"skuDO":{"skuProperties":[{"name":"颜色"}],"skuList":[{"id":"1"},{"id":"2"}]}}}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
client := &ClientImpl{HTTPClient: server.Client(), ItemDetailURL: server.URL}
|
||||
got, err := client.DetectItemMultiSpec(context.Background(), "_m_h5_tk=token_1", "item-1")
|
||||
if err != nil || !got {
|
||||
t.Fatalf("got=%v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectItemMultiSpecSignals(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
data any
|
||||
want bool
|
||||
}{
|
||||
{name: "explicit", data: map[string]any{"multiSKU": true}, want: true},
|
||||
{name: "two skus", data: map[string]any{"skuList": []any{1, 2}}, want: true},
|
||||
{name: "sku props", data: map[string]any{"skuDO": map[string]any{"props": []any{"颜色"}}}, want: true},
|
||||
{name: "single", data: map[string]any{"multiSKU": false, "skuList": []any{1}}, want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := detectItemMultiSpec(tc.data); got != tc.want {
|
||||
t.Fatalf("got=%v want=%v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectItemMultiSpecRejectsMissingToken(t *testing.T) {
|
||||
client := &ClientImpl{}
|
||||
if _, err := client.DetectItemMultiSpec(context.Background(), "unb=1", "item-1"); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
}
|
||||
@@ -237,6 +237,7 @@ func parseItemList(data map[string]any) []ItemListItem {
|
||||
ItemDetail: string(detailJSON),
|
||||
AuctionType: mtopString(cardData["auctionType"]),
|
||||
ItemStatus: mtopInt(cardData["itemStatus"]),
|
||||
IsMultiSpec: detectItemMultiSpec(cardData),
|
||||
})
|
||||
}
|
||||
return items
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
// Package mtop: 卖家订单列表域 — 从卖家工作台发现并解析订单。
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
const soldOrdersReferer = "https://seller.goofish.com/?site=COMMONPRO#/seller-trade/order-manage"
|
||||
|
||||
// SoldOrderFetcher 是订单同步使用的可选能力,不扩展基础 Client 接口,避免影响其他调用方的 mock。
|
||||
type SoldOrderFetcher interface {
|
||||
FetchSoldOrdersPage(ctx context.Context, cookies string, pageNumber, pageSize int) (*SoldOrdersPage, error)
|
||||
}
|
||||
|
||||
// SoldOrdersPage 是一页卖家订单列表。
|
||||
type SoldOrdersPage struct {
|
||||
Items []SoldOrder
|
||||
NextPage bool
|
||||
TotalCount int
|
||||
}
|
||||
|
||||
// SoldOrder 是订单列表可直接落库的字段。
|
||||
type SoldOrder struct {
|
||||
OrderID string
|
||||
ItemID string
|
||||
BuyerID string
|
||||
OrderStatus string
|
||||
Quantity string
|
||||
Amount string
|
||||
ReceiverName string
|
||||
ReceiverPhone string
|
||||
ReceiverAddr string
|
||||
ReceiverCity string
|
||||
IsBargain bool
|
||||
PlatformStatus string
|
||||
}
|
||||
|
||||
var _ SoldOrderFetcher = (*ClientImpl)(nil)
|
||||
|
||||
// FetchSoldOrdersPage 获取卖家已售订单。该能力只使用调用方传入的 Cookie 签名,
|
||||
// 不刷新 token、不合并 Set-Cookie,也不持久化 Cookie。
|
||||
func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pageNumber, pageSize int) (*SoldOrdersPage, error) {
|
||||
if pageNumber < 1 {
|
||||
pageNumber = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 30
|
||||
}
|
||||
token := protocol.SignToken(cookies)
|
||||
if token == "" {
|
||||
return nil, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取订单列表")
|
||||
}
|
||||
payload := map[string]any{
|
||||
"pageNumber": pageNumber,
|
||||
"rowsPerPage": pageSize,
|
||||
"orderIds": "",
|
||||
"queryCode": "ALL",
|
||||
"orderSearchParam": "{}",
|
||||
}
|
||||
rawPayload, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dataVal := string(rawPayload)
|
||||
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
sign := protocol.GenerateSign(timestamp, token, dataVal)
|
||||
endpoint := c.SoldOrdersURL
|
||||
if endpoint == "" {
|
||||
endpoint = SoldOrdersAPI
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildSoldOrdersQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
setCommonHeaders(req, cookies)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Origin", "https://seller.goofish.com")
|
||||
req.Header.Set("Referer", soldOrdersReferer)
|
||||
req.Header.Set("idle_site_biz_code", "COMMONPRO")
|
||||
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("订单列表请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := readMTopBody(resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var decoded struct {
|
||||
Ret []string `json:"ret"`
|
||||
Data struct {
|
||||
Module map[string]any `json:"module"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||
return nil, fmt.Errorf("解析订单列表响应失败: %w (body=%s)", err, truncate(string(raw), 300))
|
||||
}
|
||||
if !hasMTopSuccess(decoded.Ret) {
|
||||
return nil, fmt.Errorf("订单列表接口返回非成功: ret=%v", decoded.Ret)
|
||||
}
|
||||
module := decoded.Data.Module
|
||||
rawItems, _ := module["items"].([]any)
|
||||
items := make([]SoldOrder, 0, len(rawItems))
|
||||
for _, rawItem := range rawItems {
|
||||
item, ok := parseSoldOrder(rawItem)
|
||||
if ok {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
return &SoldOrdersPage{
|
||||
Items: items,
|
||||
NextPage: mtopBool(module["nextPage"]),
|
||||
TotalCount: mtopInt(module["totalCount"]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func buildSoldOrdersQuery(timestamp, sign string) string {
|
||||
values := url.Values{
|
||||
"jsv": {"2.7.2"},
|
||||
"appKey": {protocol.SignAppKey},
|
||||
"t": {timestamp},
|
||||
"sign": {sign},
|
||||
"v": {"1.0"},
|
||||
"type": {"json"},
|
||||
"accountSite": {"xianyu"},
|
||||
"dataType": {"json"},
|
||||
"timeout": {"20000"},
|
||||
"api": {"mtop.taobao.idle.trade.merchant.sold.get"},
|
||||
"valueType": {"string"},
|
||||
"sessionOption": {"AutoLoginOnly"},
|
||||
"spm_cnt": {"a21107h.42831410.0.0"},
|
||||
}
|
||||
return values.Encode()
|
||||
}
|
||||
|
||||
func parseSoldOrder(raw any) (SoldOrder, bool) {
|
||||
item, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
return SoldOrder{}, false
|
||||
}
|
||||
common, _ := item["commonData"].(map[string]any)
|
||||
buyer, _ := item["buyerInfoVO"].(map[string]any)
|
||||
price, _ := item["priceVO"].(map[string]any)
|
||||
rights, _ := item["rightVO"].(map[string]any)
|
||||
orderID := strings.TrimSpace(mtopString(common["orderId"]))
|
||||
if orderID == "" {
|
||||
return SoldOrder{}, false
|
||||
}
|
||||
rawStatus := strings.TrimSpace(mtopString(common["orderStatus"]))
|
||||
status := normalizeSoldOrderStatus(rawStatus, mtopBool(common["inRefund"]))
|
||||
amount := firstMTopString(price, "totalPrice", "confirmFee", "auctionPrice")
|
||||
quantity := firstMTopString(price, "buyNum", "quantity")
|
||||
if quantity == "" || quantity == "0" {
|
||||
quantity = "1"
|
||||
}
|
||||
isBargain := false
|
||||
buttons, _ := rights["btnList"].([]any)
|
||||
for _, rawButton := range buttons {
|
||||
button, _ := rawButton.(map[string]any)
|
||||
if strings.EqualFold(mtopString(button["tradeAction"]), "SKIP_PIN") {
|
||||
isBargain = true
|
||||
break
|
||||
}
|
||||
}
|
||||
return SoldOrder{
|
||||
OrderID: orderID,
|
||||
ItemID: strings.TrimSpace(mtopString(common["itemId"])),
|
||||
BuyerID: strings.TrimSpace(mtopString(buyer["buyerId"])),
|
||||
OrderStatus: status,
|
||||
Quantity: quantity,
|
||||
Amount: amount,
|
||||
ReceiverName: firstMTopString(buyer, "name", "receiverName"),
|
||||
ReceiverPhone: firstMTopString(buyer, "phone", "receiverPhone"),
|
||||
ReceiverAddr: firstMTopString(buyer, "address", "receiverAddress"),
|
||||
ReceiverCity: firstMTopString(buyer, "city", "receiverCity"),
|
||||
IsBargain: isBargain,
|
||||
PlatformStatus: rawStatus,
|
||||
}, true
|
||||
}
|
||||
|
||||
func normalizeSoldOrderStatus(raw string, inRefund bool) string {
|
||||
if inRefund {
|
||||
return "refunding"
|
||||
}
|
||||
switch strings.TrimSpace(raw) {
|
||||
case "待付款", "处理中":
|
||||
return "processing"
|
||||
case "待发货", "已付款":
|
||||
return "pending_ship"
|
||||
case "已发货":
|
||||
return "shipped"
|
||||
case "交易成功", "已完成":
|
||||
return "completed"
|
||||
case "交易关闭", "已关闭", "退款关闭", "退款成功", "已退款":
|
||||
return "cancelled"
|
||||
case "退款中":
|
||||
return "refunding"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
func firstMTopString(values map[string]any, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if value := strings.TrimSpace(mtopString(values[key])); value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func mtopBool(value any) bool {
|
||||
switch typed := value.(type) {
|
||||
case bool:
|
||||
return typed
|
||||
case float64:
|
||||
return typed != 0
|
||||
case int:
|
||||
return typed != 0
|
||||
case string:
|
||||
normalized := strings.ToLower(strings.TrimSpace(typed))
|
||||
return normalized == "true" || normalized == "1" || normalized == "yes"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFetchSoldOrdersPageRequestAndParse(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("api") != "mtop.taobao.idle.trade.merchant.sold.get" || r.URL.Query().Get("sign") == "" {
|
||||
t.Errorf("query=%s", r.URL.RawQuery)
|
||||
}
|
||||
if r.Header.Get("Origin") != "https://seller.goofish.com" || r.Header.Get("idle_site_biz_code") != "COMMONPRO" {
|
||||
t.Errorf("headers=%v", r.Header)
|
||||
}
|
||||
rawBody, _ := io.ReadAll(r.Body)
|
||||
form, _ := url.ParseQuery(string(rawBody))
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal([]byte(form.Get("data")), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload["pageNumber"] != float64(2) || payload["rowsPerPage"] != float64(30) || payload["queryCode"] != "ALL" {
|
||||
t.Errorf("payload=%+v", payload)
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"true","totalCount":"31","items":[{`+
|
||||
`"commonData":{"orderId":"order-1","itemId":"item-1","orderStatus":"待发货","inRefund":"false"},`+
|
||||
`"buyerInfoVO":{"buyerId":"buyer-1","name":"李四","phone":"13900000000","address":"杭州市"},`+
|
||||
`"priceVO":{"totalPrice":"29.90","buyNum":"3"},"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := &ClientImpl{HTTPClient: server.Client(), SoldOrdersURL: server.URL}
|
||||
page, err := client.FetchSoldOrdersPage(context.Background(), "unb=1; _m_h5_tk=token_1;", 2, 30)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !page.NextPage || page.TotalCount != 31 || len(page.Items) != 1 {
|
||||
t.Fatalf("page=%+v", page)
|
||||
}
|
||||
item := page.Items[0]
|
||||
if item.OrderID != "order-1" || item.ItemID != "item-1" || item.OrderStatus != "pending_ship" ||
|
||||
item.Quantity != "3" || item.Amount != "29.90" || !item.IsBargain || item.ReceiverName != "李四" {
|
||||
t.Fatalf("item=%+v", item)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchSoldOrdersPageRejectsMissingTokenAndFailure(t *testing.T) {
|
||||
client := &ClientImpl{}
|
||||
if _, err := client.FetchSoldOrdersPage(context.Background(), "unb=1", 1, 30); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"ret":["FAIL_BIZ_ERROR::失败"]}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
client = &ClientImpl{HTTPClient: server.Client(), SoldOrdersURL: server.URL}
|
||||
if _, err := client.FetchSoldOrdersPage(context.Background(), "_m_h5_tk=token_1", 1, 30); err == nil || !strings.Contains(err.Error(), "非成功") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeSoldOrderStatus(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"待付款": "processing", "待发货": "pending_ship", "已发货": "shipped",
|
||||
"交易成功": "completed", "退款成功": "cancelled", "退款中": "refunding",
|
||||
}
|
||||
for input, want := range cases {
|
||||
if got := normalizeSoldOrderStatus(input, false); got != want {
|
||||
t.Fatalf("input=%s got=%s want=%s", input, got, want)
|
||||
}
|
||||
}
|
||||
if got := normalizeSoldOrderStatus("待发货", true); got != "refunding" {
|
||||
t.Fatalf("inRefund got=%s", got)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -21,20 +22,125 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do"
|
||||
SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do"
|
||||
SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do"
|
||||
defaultRequestTimout = 20 * time.Second
|
||||
maxRenewBodyBytes = 2 << 20
|
||||
HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do"
|
||||
SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do"
|
||||
SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do"
|
||||
QueryLoginSettingsURL = "https://passport.goofish.com/ac/account/queryLoginSettings.do"
|
||||
defaultRequestTimout = 2 * time.Second
|
||||
maxRenewBodyBytes = 2 << 20
|
||||
)
|
||||
|
||||
// Service 是 Cookie 接口续期服务。零值可用;测试可覆盖 URL 和 HTTPClient。
|
||||
type Service struct {
|
||||
HTTPClient *http.Client
|
||||
HasLoginURL string
|
||||
SilentHasLoginURL string
|
||||
SetLoginSettingsURL string
|
||||
RetryDelay time.Duration
|
||||
HTTPClient *http.Client
|
||||
HasLoginURL string
|
||||
SilentHasLoginURL string
|
||||
QueryLoginSettingsURL string
|
||||
SetLoginSettingsURL string
|
||||
DocumentReferer string
|
||||
RetryDelay time.Duration
|
||||
}
|
||||
|
||||
type LongLoginSettings struct {
|
||||
CanOpenLongLogin bool `json:"can_open_long_login"`
|
||||
Enabled bool `json:"enabled"`
|
||||
NewCookies string `json:"-"`
|
||||
SetCookies []string `json:"-"`
|
||||
}
|
||||
|
||||
// QueryLongLoginSettings 对齐官网个人信息弹窗的“保存登录信息”查询。
|
||||
func (s Service) QueryLongLoginSettings(ctx context.Context, cookiesStr string) (*LongLoginSettings, error) {
|
||||
return s.longLoginRequest(ctx, cookiesStr, nil)
|
||||
}
|
||||
|
||||
// SetLongLoginSettings 中 status=0 表示开启,status=1 表示关闭。
|
||||
func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, enabled bool) (*LongLoginSettings, error) {
|
||||
status := "1"
|
||||
if enabled {
|
||||
status = "0"
|
||||
}
|
||||
return s.longLoginRequest(ctx, cookiesStr, &status)
|
||||
}
|
||||
|
||||
func (s Service) longLoginRequest(ctx context.Context, cookiesStr string, status *string) (*LongLoginSettings, error) {
|
||||
target := s.urlOrDefault(s.QueryLoginSettingsURL, QueryLoginSettingsURL)
|
||||
var body io.Reader
|
||||
if status != nil {
|
||||
target = s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL)
|
||||
body = strings.NewReader("status=" + url.QueryEscape(*status))
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := req.URL.Query()
|
||||
q.Set("fromSite", "77")
|
||||
q.Set("appName", "xianyu")
|
||||
q.Set("bizEntrance", "web")
|
||||
req.URL.RawQuery = q.Encode()
|
||||
setSilentHasLoginHeaders(req, cookiesStr, s.documentReferer())
|
||||
if status != nil {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
hc := s.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: defaultRequestTimout}
|
||||
}
|
||||
requestCtx, cancel := context.WithTimeout(req.Context(), defaultRequestTimout)
|
||||
defer cancel()
|
||||
resp, err := hc.Do(req.Clone(requestCtx))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("保存登录信息请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := readRenewBody(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("保存登录信息 HTTP 状态异常: %d", resp.StatusCode)
|
||||
}
|
||||
value, ok := findReturnValue(raw)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("保存登录信息响应缺少 returnValue")
|
||||
}
|
||||
canOpen, _ := value["canOpenLongLogin"].(bool)
|
||||
enabledValue, hasEnabled := value["hasLongTokenLogin"].(bool)
|
||||
if status != nil && !hasEnabled {
|
||||
enabledValue = *status == "0"
|
||||
}
|
||||
setCookies := filterValidSetCookies(resp.Header.Values("Set-Cookie"))
|
||||
return &LongLoginSettings{
|
||||
CanOpenLongLogin: canOpen,
|
||||
Enabled: enabledValue,
|
||||
NewCookies: MergeSetCookies(cookiesStr, setCookies),
|
||||
SetCookies: setCookies,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func findReturnValue(raw []byte) (map[string]any, bool) {
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return nil, false
|
||||
}
|
||||
return findMapChild(payload, "returnValue", 0)
|
||||
}
|
||||
|
||||
func findMapChild(parent map[string]any, key string, depth int) (map[string]any, bool) {
|
||||
if parent == nil || depth > 6 {
|
||||
return nil, false
|
||||
}
|
||||
if value, ok := parent[key].(map[string]any); ok {
|
||||
return value, true
|
||||
}
|
||||
for _, child := range parent {
|
||||
if nested, ok := child.(map[string]any); ok {
|
||||
if value, found := findMapChild(nested, key, depth+1); found {
|
||||
return value, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Result 描述一次接口续期的完整结果。
|
||||
@@ -45,6 +151,7 @@ type Result struct {
|
||||
RenewMethod string
|
||||
NewCookies string
|
||||
UpdatedCookieNames []string
|
||||
SetCookies []string
|
||||
StepDetails []StepResult
|
||||
Message string
|
||||
ResponseText string
|
||||
@@ -118,6 +225,7 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string) (*Result,
|
||||
RenewMethod: "auto_login_plugin",
|
||||
NewCookies: newCookies,
|
||||
UpdatedCookieNames: ChangedCookieNames(cookiesStr, newCookies),
|
||||
SetCookies: append([]string(nil), call.SetCookies...),
|
||||
StepDetails: []StepResult{call.Step},
|
||||
Message: message,
|
||||
ResponseText: string(call.Body),
|
||||
@@ -140,8 +248,17 @@ func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason s
|
||||
}
|
||||
|
||||
func cookieTimeAfter(raw string, now time.Time) bool {
|
||||
millis, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
|
||||
return err == nil && millis > now.UnixMilli()
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return false
|
||||
}
|
||||
millis, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
// plugin.js 使用 Invalid Date <= now;结果为 false,因此非空异常值
|
||||
// 会继续进入对应续期分支。
|
||||
return true
|
||||
}
|
||||
return millis > now.UnixMilli()
|
||||
}
|
||||
|
||||
func autoLoginSkipMessage(reason string) string {
|
||||
@@ -167,7 +284,7 @@ func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (ca
|
||||
return callResult{}, err
|
||||
}
|
||||
q := req.URL.Query()
|
||||
q.Set("documentReferer", "https://www.goofish.com/")
|
||||
q.Set("documentReferer", s.documentReferer())
|
||||
q.Set("appName", "xianyu")
|
||||
q.Set("appEntrance", "xianyu_sdkSilent")
|
||||
q.Set("fromSite", "0")
|
||||
@@ -181,7 +298,7 @@ func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (ca
|
||||
return callResult{}, fmt.Errorf("未知静默续期模式: %s", mode)
|
||||
}
|
||||
req.URL.RawQuery = q.Encode()
|
||||
setSilentHasLoginHeaders(req, cookiesStr)
|
||||
setSilentHasLoginHeaders(req, cookiesStr, s.documentReferer())
|
||||
return s.doRenewRequest(req, "silentHasLogin")
|
||||
}
|
||||
|
||||
@@ -190,11 +307,10 @@ func (s Service) doRenewRequest(req *http.Request, name string) (callResult, err
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: defaultRequestTimout}
|
||||
}
|
||||
client := *hc
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
requestCtx, cancel := context.WithTimeout(req.Context(), defaultRequestTimout)
|
||||
defer cancel()
|
||||
req = req.Clone(requestCtx)
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return callResult{}, fmt.Errorf("%s 请求失败: %w", name, err)
|
||||
}
|
||||
@@ -209,7 +325,7 @@ func (s Service) doRenewRequest(req *http.Request, name string) (callResult, err
|
||||
HTTPStatus: resp.StatusCode,
|
||||
SetCookieCount: len(setCookies),
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
step.Message = fmt.Sprintf("HTTP状态异常: %d", resp.StatusCode)
|
||||
return callResult{Step: step, SetCookies: setCookies, Body: body}, nil
|
||||
}
|
||||
@@ -246,8 +362,7 @@ func renewBusinessOK(body []byte) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
ok, _ := content["success"].(bool)
|
||||
return ok
|
||||
return false
|
||||
}
|
||||
|
||||
func mtopInt(v any) int {
|
||||
@@ -265,14 +380,15 @@ func mtopInt(v any) int {
|
||||
}
|
||||
}
|
||||
|
||||
func setSilentHasLoginHeaders(req *http.Request, cookiesStr string) {
|
||||
func setSilentHasLoginHeaders(req *http.Request, cookiesStr, documentReferer string) {
|
||||
xianyu.ApplyBrowserFingerprint(req.Header)
|
||||
req.Header.Set("Accept", "*/*")
|
||||
req.Header.Set("Accept-Language", "en,zh-CN;q=0.9,zh;q=0.8,ru;q=0.7")
|
||||
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
req.Header.Set("Pragma", "no-cache")
|
||||
req.Header.Set("Priority", "u=1, i")
|
||||
req.Header.Set("Referer", "https://www.goofish.com/")
|
||||
req.Header.Set("Origin", "https://www.goofish.com")
|
||||
req.Header.Set("Referer", documentReferer)
|
||||
req.Header.Set("sec-fetch-dest", "empty")
|
||||
req.Header.Set("sec-fetch-mode", "cors")
|
||||
req.Header.Set("sec-fetch-site", "same-site")
|
||||
@@ -286,6 +402,13 @@ func (s Service) urlOrDefault(v, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func (s Service) documentReferer() string {
|
||||
if strings.TrimSpace(s.DocumentReferer) != "" {
|
||||
return strings.TrimSpace(s.DocumentReferer)
|
||||
}
|
||||
return "https://www.goofish.com/im"
|
||||
}
|
||||
|
||||
func readRenewBody(r io.Reader) ([]byte, error) {
|
||||
body, err := io.ReadAll(io.LimitReader(r, maxRenewBodyBytes+1))
|
||||
if err != nil {
|
||||
@@ -312,7 +435,7 @@ func filterValidSetCookies(setCookies []string) []string {
|
||||
}
|
||||
out := make([]string, 0, len(setCookies))
|
||||
for _, sc := range setCookies {
|
||||
if strings.Contains(sc, "Max-Age=0") || strings.Contains(sc, "1970") {
|
||||
if strings.TrimSpace(sc) == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, sc)
|
||||
@@ -325,19 +448,15 @@ func filterValidSetCookies(setCookies []string) []string {
|
||||
func MergeSetCookies(original string, setCookies []string) string {
|
||||
cookies := protocol.TransCookies(original)
|
||||
for _, sc := range setCookies {
|
||||
pair := sc
|
||||
if i := strings.Index(pair, ";"); i >= 0 {
|
||||
pair = pair[:i]
|
||||
}
|
||||
name, val, ok := strings.Cut(pair, "=")
|
||||
if !ok {
|
||||
parsed, err := http.ParseSetCookie(sc)
|
||||
if err != nil || strings.TrimSpace(parsed.Name) == "" {
|
||||
continue
|
||||
}
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
continue
|
||||
if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) {
|
||||
delete(cookies, parsed.Name)
|
||||
} else {
|
||||
cookies[parsed.Name] = parsed.Value
|
||||
}
|
||||
cookies[name] = strings.TrimSpace(val)
|
||||
}
|
||||
return marshalCookies(cookies)
|
||||
}
|
||||
@@ -347,8 +466,15 @@ func ChangedCookieNames(original, newCookies string) []string {
|
||||
oldMap := protocol.TransCookies(original)
|
||||
newMap := protocol.TransCookies(newCookies)
|
||||
changed := make([]string, 0)
|
||||
for k, v := range newMap {
|
||||
if oldMap[k] != v {
|
||||
seen := make(map[string]struct{}, len(oldMap)+len(newMap))
|
||||
for k := range oldMap {
|
||||
seen[k] = struct{}{}
|
||||
}
|
||||
for k := range newMap {
|
||||
seen[k] = struct{}{}
|
||||
}
|
||||
for k := range seen {
|
||||
if oldMap[k] != newMap[k] {
|
||||
changed = append(changed, k)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
|
||||
{name: "fatigue", cookies: map[string]string{"sdkSilent": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10), "havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantReason: "fatigue"},
|
||||
{name: "havana", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
|
||||
{name: "cookie3 backup", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10), "cookie3_bak_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeCookie3},
|
||||
{name: "expired", cookies: map[string]string{"havana_lgc_exp": "bad", "cookie3_bak_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)}, wantReason: "long_login_expired"},
|
||||
{name: "malformed long-login expiry follows browser Invalid Date branch", cookies: map[string]string{"havana_lgc_exp": "bad", "cookie3_bak_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -41,6 +41,51 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
if r.Method != http.MethodPost {
|
||||
t.Fatalf("method=%s", r.Method)
|
||||
}
|
||||
if r.URL.Query().Get("fromSite") != "77" || r.URL.Query().Get("appName") != "xianyu" || r.URL.Query().Get("bizEntrance") != "web" {
|
||||
t.Fatalf("query=%s", r.URL.RawQuery)
|
||||
}
|
||||
if r.Header.Get("Origin") != "https://www.goofish.com" || r.Header.Get("Referer") != "https://www.goofish.com/im" {
|
||||
t.Fatalf("origin/referer=%q/%q", r.Header.Get("Origin"), r.Header.Get("Referer"))
|
||||
}
|
||||
if !strings.Contains(r.Header.Get("Cookie"), "unb=1") {
|
||||
t.Fatalf("Cookie=%q", r.Header.Get("Cookie"))
|
||||
}
|
||||
if strings.Contains(r.URL.Path, "set") {
|
||||
if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" {
|
||||
t.Fatalf("set form=%v err=%v", r.Form, err)
|
||||
}
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "havana_lgc_exp", Value: futureMillis(24 * time.Hour), Path: "/", HttpOnly: true})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
service := Service{
|
||||
HTTPClient: srv.Client(),
|
||||
QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
|
||||
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
|
||||
DocumentReferer: "https://www.goofish.com/im",
|
||||
}
|
||||
queried, err := service.QueryLongLoginSettings(context.Background(), "unb=1")
|
||||
if err != nil || !queried.CanOpenLongLogin || !queried.Enabled {
|
||||
t.Fatalf("query result=%+v err=%v", queried, err)
|
||||
}
|
||||
set, err := service.SetLongLoginSettings(context.Background(), queried.NewCookies, true)
|
||||
if err != nil || !set.Enabled || len(set.SetCookies) != 1 || !strings.Contains(set.NewCookies, "havana_lgc_exp=") {
|
||||
t.Fatalf("set result=%+v err=%v", set, err)
|
||||
}
|
||||
if calls.Load() != 2 {
|
||||
t.Fatalf("calls=%d", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "native-browser-ua", SecChUA: `"Chromium";v="999"`, Platform: "macOS", Mobile: "?0"})
|
||||
var calls atomic.Int32
|
||||
@@ -52,6 +97,9 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
|
||||
if r.URL.Query().Get("skipSessionFilter") != "" || r.URL.Query().Get("c2r") != "" {
|
||||
t.Fatalf("havana mode included cookie3 flags: %s", r.URL.RawQuery)
|
||||
}
|
||||
if got := r.URL.Query().Get("documentReferer"); got != "https://www.goofish.com/im" {
|
||||
t.Fatalf("documentReferer=%q", got)
|
||||
}
|
||||
if got := r.Header.Get("User-Agent"); got != "native-browser-ua" {
|
||||
t.Fatalf("User-Agent=%q", got)
|
||||
}
|
||||
@@ -63,7 +111,7 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, DocumentReferer: "https://www.goofish.com/im", RetryDelay: -1}
|
||||
input := "unb=1; havana_lgc_exp=" + futureMillis(time.Hour)
|
||||
res, err := svc.RenewAPIFirst(context.Background(), input)
|
||||
if err != nil {
|
||||
@@ -140,6 +188,28 @@ func TestMergeSetCookies(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeSetCookiesAppliesServerDeletion(t *testing.T) {
|
||||
got := MergeSetCookies("unb=1; stale=a; expired=b", []string{
|
||||
"stale=; Max-Age=0; Path=/",
|
||||
"expired=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/",
|
||||
})
|
||||
if strings.Contains(got, "stale=") || strings.Contains(got, "expired=") {
|
||||
t.Fatalf("deleted cookies survived: %q", got)
|
||||
}
|
||||
if changed := strings.Join(ChangedCookieNames("unb=1; stale=a; expired=b", got), ","); changed != "expired,stale" {
|
||||
t.Fatalf("ChangedCookieNames=%s", changed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewBusinessOKMatchesOfficialPlugin(t *testing.T) {
|
||||
if renewBusinessOK([]byte(`{"content":{"success":true}}`)) {
|
||||
t.Fatal("official plugin requires processFinished=true and resultCode=100")
|
||||
}
|
||||
if !renewBusinessOK([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`)) {
|
||||
t.Fatal("official success payload was rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewBodyLimit(t *testing.T) {
|
||||
_, err := readRenewBody(strings.NewReader(strings.Repeat("x", maxRenewBodyBytes+1)))
|
||||
if err == nil || !strings.Contains(err.Error(), fmt.Sprint(maxRenewBodyBytes>>20)) {
|
||||
|
||||
+379
-253
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -19,17 +20,17 @@ import (
|
||||
)
|
||||
|
||||
// WSURL 闲鱼 IM WebSocket 地址。
|
||||
const WSURL = "wss://wss-goofish.dingtalk.com/"
|
||||
const WSURL = "wss://wss-goofish.dingtalk.com:443"
|
||||
|
||||
const (
|
||||
wsOpenTimeout = 30 * time.Second
|
||||
regResponseTimeout = 30 * time.Second
|
||||
protocolPingInterval = 20 * time.Second
|
||||
protocolPingTimeout = 15 * time.Second
|
||||
wsOpenTimeout = 30 * time.Second
|
||||
regResponseTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// 变量仅用于让单元测试无需真实等待 10 秒;生产值严格对齐参考实现。
|
||||
var heartbeatRetryInterval = 5 * time.Second
|
||||
var (
|
||||
heartbeatResponseTimeout = 30 * time.Second
|
||||
batchConnectDelays = []time.Duration{0, 200 * time.Millisecond, 900 * time.Millisecond, 1500 * time.Millisecond, 4 * time.Second}
|
||||
)
|
||||
|
||||
// RegAppKey WS /reg 用的 app-key。
|
||||
const RegAppKey = "444e9908a51d1cb236a27862abc769c9"
|
||||
@@ -44,18 +45,28 @@ type Config struct {
|
||||
|
||||
// Conn 包装一条已注册的 WebSocket 连接。
|
||||
type Conn struct {
|
||||
ws *websocket.Conn
|
||||
cfg Config
|
||||
logger *slog.Logger
|
||||
sendMu sync.Mutex
|
||||
preReadMu sync.Mutex
|
||||
preRead []bufferedFrame
|
||||
recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
|
||||
ws *websocket.Conn
|
||||
cfg Config
|
||||
logger *slog.Logger
|
||||
sendMu sync.Mutex
|
||||
recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
|
||||
|
||||
readCtx context.Context
|
||||
readCancel context.CancelFunc
|
||||
readDone chan struct{}
|
||||
initOnce sync.Once
|
||||
readErrMu sync.Mutex
|
||||
readErr error
|
||||
|
||||
pendingMu sync.Mutex
|
||||
pending map[string]chan map[string]any
|
||||
pushes chan incomingFrame
|
||||
}
|
||||
|
||||
type bufferedFrame struct {
|
||||
type incomingFrame struct {
|
||||
messageType websocket.MessageType
|
||||
data []byte
|
||||
parsed map[string]any
|
||||
}
|
||||
|
||||
// SetRecorder 设置帧记录器。
|
||||
@@ -63,135 +74,208 @@ func (c *Conn) SetRecorder(rec func(direction, rawText, parsedJSON, parseStatus,
|
||||
c.recorder = rec
|
||||
}
|
||||
|
||||
// Dial 建立并注册 WS 连接:握手 → /reg → /r/SyncStatus/ackDiff。
|
||||
// Dial 保留旧的一步式入口;新账号主循环使用 Open → 获取 token → Register,
|
||||
// 从而与官网 authConnect 的顺序一致。
|
||||
func Dial(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
// 参考实现的 WEBSOCKET_HEADERS 为空,只在拨号前加入 Cookie。额外伪造
|
||||
// Origin/User-Agent 等头会改变服务端看到的连接指纹。
|
||||
hdr := websocketHeaders(cfg.CookieStr)
|
||||
|
||||
logger.Info("正在连接闲鱼 WebSocket", "url", WSURL)
|
||||
dialCtx, cancel := context.WithTimeout(ctx, wsOpenTimeout)
|
||||
defer cancel()
|
||||
c, _, err := websocket.Dial(dialCtx, WSURL, &websocket.DialOptions{HTTPHeader: hdr})
|
||||
conn, err := Open(ctx, cfg, logger)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("WS dial: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
// 闲鱼消息多为文本 JSON。
|
||||
c.SetReadLimit(8 << 20) // 8 MiB,宽松上限
|
||||
|
||||
conn := &Conn{ws: c, cfg: cfg, logger: logger, recorder: cfg.Recorder}
|
||||
if err := conn.register(ctx); err != nil {
|
||||
_ = c.CloseNow()
|
||||
if err := conn.Register(ctx, cfg.DeviceID, cfg.AccessToken); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func websocketHeaders(cookieStr string) http.Header {
|
||||
// Open 按官网 batchConnectWs 策略并行打开最多五条原生 WebSocket,采用最先
|
||||
// 成功的连接并关闭冗余连接。此阶段不请求 token,也不发送 /reg。
|
||||
func Open(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
logger.Info("正在连接闲鱼 WebSocket", "url", WSURL)
|
||||
return openBatch(ctx, WSURL, cfg, logger)
|
||||
}
|
||||
|
||||
func websocketHeaders() http.Header {
|
||||
hdr := http.Header{}
|
||||
hdr.Set("Cookie", strings.NewReplacer("\n", "", "\r", "").Replace(cookieStr))
|
||||
hdr.Set("Origin", "https://www.goofish.com")
|
||||
if ua := xianyu.CurrentBrowserFingerprint().UserAgent; ua != "" {
|
||||
hdr.Set("User-Agent", ua)
|
||||
}
|
||||
return hdr
|
||||
}
|
||||
|
||||
// register 发送 /reg 与 ackDiff。
|
||||
var (
|
||||
chromeVersionPattern = regexp.MustCompile(`(?:Chrome|CriOS)/([\d.]+)`)
|
||||
edgeVersionPattern = regexp.MustCompile(`Edg(?:e|A|iOS)?/([\d.]+)`)
|
||||
firefoxVersionPattern = regexp.MustCompile(`Firefox/([\d.]+)`)
|
||||
safariVersionPattern = regexp.MustCompile(`Version/([\d.]+).*Safari`)
|
||||
macVersionPattern = regexp.MustCompile(`Mac OS X[ /]([\d_\.]+)`)
|
||||
windowsVersionPattern = regexp.MustCompile(`Windows NT ([\d.]+)`)
|
||||
androidVersionPattern = regexp.MustCompile(`Android[ /]([\d.]+)`)
|
||||
)
|
||||
|
||||
// OfficialRegistrationUA mirrors IMPaaS 2.2.0's ua-parser-js composition.
|
||||
// The raw UA (and therefore its browser version) comes from local Chromium;
|
||||
// all wrapper fields and ordering are fixed to the official web implementation.
|
||||
func OfficialRegistrationUA(rawUA string) string {
|
||||
rawUA = strings.TrimSpace(rawUA)
|
||||
if rawUA == "" {
|
||||
return ""
|
||||
}
|
||||
osName, osVersion := parseOfficialOS(rawUA)
|
||||
browserName, browserVersion := parseOfficialBrowser(rawUA)
|
||||
return strings.Join([]string{
|
||||
rawUA,
|
||||
"DingTalk(2.2.0)",
|
||||
fmt.Sprintf("OS(%s/%s)", osName, osVersion),
|
||||
fmt.Sprintf("Browser(%s/%s)", browserName, browserVersion),
|
||||
"DingWeb/2.2.0",
|
||||
"DingWeb/2.2.0",
|
||||
}, " ")
|
||||
}
|
||||
|
||||
func parseOfficialOS(ua string) (string, string) {
|
||||
if match := macVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
|
||||
return "Mac OS", strings.ReplaceAll(match[1], "_", ".")
|
||||
}
|
||||
if match := windowsVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
|
||||
versions := map[string]string{"10.0": "10", "6.3": "8.1", "6.2": "8", "6.1": "7", "6.0": "Vista", "5.1": "XP"}
|
||||
if version := versions[match[1]]; version != "" {
|
||||
return "Windows", version
|
||||
}
|
||||
return "Windows", match[1]
|
||||
}
|
||||
if match := androidVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
|
||||
return "Android", match[1]
|
||||
}
|
||||
if strings.Contains(ua, "Linux") {
|
||||
return "Linux", "other"
|
||||
}
|
||||
return "other", "other"
|
||||
}
|
||||
|
||||
func parseOfficialBrowser(ua string) (string, string) {
|
||||
for _, candidate := range []struct {
|
||||
name string
|
||||
pattern *regexp.Regexp
|
||||
}{{"Edge", edgeVersionPattern}, {"Chrome", chromeVersionPattern}, {"Firefox", firefoxVersionPattern}, {"Safari", safariVersionPattern}} {
|
||||
if match := candidate.pattern.FindStringSubmatch(ua); len(match) == 2 {
|
||||
return candidate.name, match[1]
|
||||
}
|
||||
}
|
||||
return "other", "other"
|
||||
}
|
||||
|
||||
type dialResult struct {
|
||||
conn *websocket.Conn
|
||||
err error
|
||||
}
|
||||
|
||||
func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logger) (*Conn, error) {
|
||||
batchCtx, cancel := context.WithCancel(ctx)
|
||||
results := make(chan dialResult, len(batchConnectDelays))
|
||||
for _, delay := range batchConnectDelays {
|
||||
delay := delay
|
||||
go func() {
|
||||
if delay > 0 {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-batchCtx.Done():
|
||||
results <- dialResult{err: batchCtx.Err()}
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
dialCtx, dialCancel := context.WithTimeout(batchCtx, wsOpenTimeout)
|
||||
defer dialCancel()
|
||||
conn, _, err := websocket.Dial(dialCtx, target, &websocket.DialOptions{HTTPHeader: websocketHeaders()})
|
||||
results <- dialResult{conn: conn, err: err}
|
||||
}()
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
for processed := 1; processed <= len(batchConnectDelays); processed++ {
|
||||
result := <-results
|
||||
if result.err != nil {
|
||||
lastErr = result.err
|
||||
continue
|
||||
}
|
||||
cancel()
|
||||
// 继续排空结果并关闭稍后成功的冗余连接。
|
||||
remaining := len(batchConnectDelays) - processed
|
||||
go func() {
|
||||
for i := 0; i < remaining; i++ {
|
||||
result := <-results
|
||||
if result.conn != nil {
|
||||
_ = result.conn.CloseNow()
|
||||
}
|
||||
}
|
||||
}()
|
||||
result.conn.SetReadLimit(8 << 20)
|
||||
return newConn(result.conn, cfg, logger), nil
|
||||
}
|
||||
cancel()
|
||||
if lastErr == nil {
|
||||
lastErr = context.Canceled
|
||||
}
|
||||
return nil, fmt.Errorf("WS dial: %w", lastErr)
|
||||
}
|
||||
|
||||
func newConn(raw *websocket.Conn, cfg Config, logger *slog.Logger) *Conn {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
c := &Conn{ws: raw, cfg: cfg, logger: logger, recorder: cfg.Recorder}
|
||||
c.ensureReadPump()
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Conn) ensureReadPump() {
|
||||
c.initOnce.Do(func() {
|
||||
if c.logger == nil {
|
||||
c.logger = slog.Default()
|
||||
}
|
||||
c.readCtx, c.readCancel = context.WithCancel(context.Background())
|
||||
c.readDone = make(chan struct{})
|
||||
c.pending = make(map[string]chan map[string]any)
|
||||
c.pushes = make(chan incomingFrame, 128)
|
||||
go c.readPump()
|
||||
})
|
||||
}
|
||||
|
||||
// Register 发送官网最终态 /reg headers。注册后不主动构造 ackDiff。
|
||||
func (c *Conn) Register(ctx context.Context, deviceID, accessToken string) error {
|
||||
c.ensureReadPump()
|
||||
c.cfg.DeviceID = deviceID
|
||||
c.cfg.AccessToken = accessToken
|
||||
response, err := c.request(ctx, "/reg", map[string]any{
|
||||
"cache-header": "app-key token ua wv",
|
||||
"app-key": RegAppKey,
|
||||
"token": accessToken,
|
||||
"ua": OfficialRegistrationUA(xianyu.CurrentBrowserFingerprint().UserAgent),
|
||||
"dt": "j",
|
||||
"wv": "im:3,au:3,sy:6",
|
||||
"sync": "0,0;0;0;",
|
||||
"did": deviceID,
|
||||
}, nil, regResponseTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("等待 /reg 响应失败: %w", err)
|
||||
}
|
||||
code, ok := responseCode(response["code"])
|
||||
if ok && code == 200 {
|
||||
c.logger.Info("WS 注册完成")
|
||||
return nil
|
||||
}
|
||||
return newRegError(code, response)
|
||||
}
|
||||
|
||||
// register 兼容包内旧测试。
|
||||
func (c *Conn) register(ctx context.Context) error {
|
||||
regMID := protocol.GenerateMid()
|
||||
reg := map[string]any{
|
||||
"lwp": "/reg",
|
||||
"headers": map[string]any{
|
||||
"cache-header": "app-key token ua wv",
|
||||
"app-key": RegAppKey,
|
||||
"token": c.cfg.AccessToken,
|
||||
"ua": xianyu.CurrentBrowserFingerprint().UserAgent,
|
||||
"dt": "j",
|
||||
"wv": "im:3,au:3,sy:6",
|
||||
"sync": "0,0;0;0;",
|
||||
"did": c.cfg.DeviceID,
|
||||
"mid": regMID,
|
||||
},
|
||||
}
|
||||
if err := c.sendJSON(ctx, reg); err != nil {
|
||||
return fmt.Errorf("发送 /reg 失败: %w", err)
|
||||
}
|
||||
if err := c.waitForRegResponse(ctx, regMID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 官方只在 /reg 认证成功后启动后续同步。保留原有短等待,避免紧贴注册
|
||||
// 响应发送同步请求。
|
||||
select {
|
||||
case <-time.After(time.Second):
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
ackDiff := map[string]any{
|
||||
"lwp": "/r/SyncStatus/ackDiff",
|
||||
"headers": map[string]any{"mid": protocol.GenerateMid()},
|
||||
"body": []any{
|
||||
map[string]any{
|
||||
"pipeline": "sync",
|
||||
"tooLong2Tag": "PNM,1",
|
||||
"channel": "sync",
|
||||
"topic": "sync",
|
||||
"highPts": 0,
|
||||
"pts": now * 1000,
|
||||
"seq": 0,
|
||||
"timestamp": now,
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := c.sendJSON(ctx, ackDiff); err != nil {
|
||||
return fmt.Errorf("发送 ackDiff 失败: %w", err)
|
||||
}
|
||||
c.logger.Info("WS 注册完成")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) waitForRegResponse(ctx context.Context, requestMID string) error {
|
||||
regCtx, cancel := context.WithTimeout(ctx, regResponseTimeout)
|
||||
defer cancel()
|
||||
|
||||
for {
|
||||
messageType, data, err := c.ws.Read(regCtx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("等待 /reg 响应失败: %w", err)
|
||||
}
|
||||
var frame map[string]any
|
||||
if err := json.Unmarshal(data, &frame); err != nil {
|
||||
c.bufferFrame(messageType, data)
|
||||
continue
|
||||
}
|
||||
if !isRegResponse(frame, requestMID) {
|
||||
c.bufferFrame(messageType, data)
|
||||
continue
|
||||
}
|
||||
c.recordParsedIncoming(data, frame)
|
||||
code, ok := responseCode(frame["code"])
|
||||
if ok && code == 200 {
|
||||
return nil
|
||||
}
|
||||
return newRegError(code, frame)
|
||||
}
|
||||
}
|
||||
|
||||
func isRegResponse(frame map[string]any, requestMID string) bool {
|
||||
if _, ok := frame["code"]; !ok {
|
||||
return false
|
||||
}
|
||||
headers, _ := frame["headers"].(map[string]any)
|
||||
responseMIDValue, hasMID := headers["mid"]
|
||||
responseMID := strings.TrimSpace(fmt.Sprint(responseMIDValue))
|
||||
if !hasMID || responseMID == "" || responseMID == "<nil>" {
|
||||
// /reg is the only outstanding request during registration. Some gateway
|
||||
// versions omit mid on an immediate authentication failure.
|
||||
return true
|
||||
}
|
||||
return midKey(responseMID) == midKey(requestMID)
|
||||
return c.Register(ctx, c.cfg.DeviceID, c.cfg.AccessToken)
|
||||
}
|
||||
|
||||
func midKey(mid string) string {
|
||||
@@ -220,23 +304,111 @@ func responseCode(value any) (int, bool) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (c *Conn) bufferFrame(messageType websocket.MessageType, data []byte) {
|
||||
copyOfData := append([]byte(nil), data...)
|
||||
c.preReadMu.Lock()
|
||||
c.preRead = append(c.preRead, bufferedFrame{messageType: messageType, data: copyOfData})
|
||||
c.preReadMu.Unlock()
|
||||
func (c *Conn) request(ctx context.Context, path string, headers map[string]any, body any, timeout time.Duration) (map[string]any, error) {
|
||||
c.ensureReadPump()
|
||||
if headers == nil {
|
||||
headers = make(map[string]any)
|
||||
}
|
||||
mid := strings.TrimSpace(fmt.Sprint(headers["mid"]))
|
||||
if mid == "" || mid == "<nil>" {
|
||||
mid = protocol.GenerateMid()
|
||||
headers["mid"] = mid
|
||||
}
|
||||
key := midKey(mid)
|
||||
responseCh := make(chan map[string]any, 1)
|
||||
c.pendingMu.Lock()
|
||||
c.pending[key] = responseCh
|
||||
c.pendingMu.Unlock()
|
||||
defer func() {
|
||||
c.pendingMu.Lock()
|
||||
delete(c.pending, key)
|
||||
c.pendingMu.Unlock()
|
||||
}()
|
||||
|
||||
frame := map[string]any{"lwp": path, "headers": headers}
|
||||
if body != nil {
|
||||
frame["body"] = body
|
||||
}
|
||||
if err := c.sendJSON(ctx, frame); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
waitCtx := ctx
|
||||
cancel := func() {}
|
||||
if timeout > 0 {
|
||||
waitCtx, cancel = context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
defer cancel()
|
||||
select {
|
||||
case response := <-responseCh:
|
||||
return response, nil
|
||||
case <-c.readDone:
|
||||
return nil, c.connectionReadError()
|
||||
case <-waitCtx.Done():
|
||||
return nil, waitCtx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) readNext(ctx context.Context) (websocket.MessageType, []byte, error) {
|
||||
c.preReadMu.Lock()
|
||||
if len(c.preRead) > 0 {
|
||||
frame := c.preRead[0]
|
||||
c.preRead = c.preRead[1:]
|
||||
c.preReadMu.Unlock()
|
||||
return frame.messageType, frame.data, nil
|
||||
func (c *Conn) readPump() {
|
||||
defer close(c.readDone)
|
||||
for {
|
||||
messageType, data, err := c.ws.Read(c.readCtx)
|
||||
if err != nil {
|
||||
c.readErrMu.Lock()
|
||||
c.readErr = err
|
||||
c.readErrMu.Unlock()
|
||||
return
|
||||
}
|
||||
var parsed map[string]any
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
if c.recorder != nil {
|
||||
c.recorder("in", string(data), "", "non_json", err.Error())
|
||||
}
|
||||
continue
|
||||
}
|
||||
c.recordParsedIncoming(data, parsed)
|
||||
if _, hasCode := parsed["code"]; hasCode {
|
||||
if _, hasHeaders := parsed["headers"].(map[string]any); hasHeaders {
|
||||
c.dispatchResponse(parsed)
|
||||
continue
|
||||
}
|
||||
}
|
||||
incoming := incomingFrame{messageType: messageType, data: append([]byte(nil), data...), parsed: parsed}
|
||||
select {
|
||||
case c.pushes <- incoming:
|
||||
case <-c.readCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
c.preReadMu.Unlock()
|
||||
return c.ws.Read(ctx)
|
||||
}
|
||||
|
||||
func (c *Conn) dispatchResponse(frame map[string]any) bool {
|
||||
headers, _ := frame["headers"].(map[string]any)
|
||||
key := midKey(strings.TrimSpace(fmt.Sprint(headers["mid"])))
|
||||
c.pendingMu.Lock()
|
||||
ch := c.pending[key]
|
||||
if ch == nil && key == "" && len(c.pending) == 1 {
|
||||
for _, only := range c.pending {
|
||||
ch = only
|
||||
}
|
||||
}
|
||||
c.pendingMu.Unlock()
|
||||
if ch == nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case ch <- frame:
|
||||
default:
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Conn) connectionReadError() error {
|
||||
c.readErrMu.Lock()
|
||||
defer c.readErrMu.Unlock()
|
||||
if c.readErr != nil {
|
||||
return c.readErr
|
||||
}
|
||||
return fmt.Errorf("WebSocket 读取循环已结束")
|
||||
}
|
||||
|
||||
func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) {
|
||||
@@ -250,111 +422,52 @@ func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) {
|
||||
c.recorder("in", string(data), parsedJSON, "json", "")
|
||||
}
|
||||
|
||||
// HeartbeatLoop 周期性发送应用层心跳 {"lwp":"/!"},直到 ctx 取消或连续失败 maxFailures 次。
|
||||
// HeartbeatLoop 对齐官网:注册后先等待一个间隔,再发送 /! 并等待同 mid 响应;
|
||||
// 任一请求失败或 30 秒无响应即结束连接。
|
||||
func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error {
|
||||
const maxFailures = 3
|
||||
consecutive := 0
|
||||
pingCtx, cancelPing := context.WithCancel(ctx)
|
||||
defer cancelPing()
|
||||
pingErr := make(chan error, 1)
|
||||
go func() { pingErr <- c.protocolPingLoop(pingCtx) }()
|
||||
|
||||
for {
|
||||
// 参考实现连接建立后立即发送应用层心跳,成功后才等待 15 秒。
|
||||
hb := map[string]any{
|
||||
"lwp": "/!",
|
||||
"headers": map[string]any{"mid": protocol.GenerateMid()},
|
||||
}
|
||||
// 2s 超时保护。
|
||||
sendCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err := c.sendJSON(sendCtx, hb)
|
||||
cancel()
|
||||
if err != nil {
|
||||
consecutive++
|
||||
c.logger.Error("心跳发送失败", "err", err, "consecutive", consecutive)
|
||||
if consecutive >= maxFailures {
|
||||
return fmt.Errorf("心跳连续失败 %d 次", maxFailures)
|
||||
}
|
||||
if err := waitHeartbeat(ctx, pingErr, heartbeatRetryInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
consecutive = 0
|
||||
if err := waitHeartbeat(ctx, pingErr, interval); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitHeartbeat(ctx context.Context, pingErr <-chan error, delay time.Duration) error {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case err := <-pingErr:
|
||||
if err == nil {
|
||||
return fmt.Errorf("WebSocket PING 循环意外退出")
|
||||
}
|
||||
return err
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// protocolPingLoop 对齐参考库的 ping_interval=20、ping_timeout=15。
|
||||
func (c *Conn) protocolPingLoop(ctx context.Context) error {
|
||||
ticker := time.NewTicker(protocolPingInterval)
|
||||
c.ensureReadPump()
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-c.readDone:
|
||||
return c.connectionReadError()
|
||||
case <-ticker.C:
|
||||
}
|
||||
pingCtx, cancel := context.WithTimeout(ctx, protocolPingTimeout)
|
||||
err := c.ws.Ping(pingCtx)
|
||||
cancel()
|
||||
response, err := c.request(ctx, "/!", map[string]any{}, nil, heartbeatResponseTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("WebSocket PING 失败: %w", err)
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return fmt.Errorf("心跳响应失败: %w", err)
|
||||
}
|
||||
if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
|
||||
return fmt.Errorf("心跳响应状态异常: %d", code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ReceiveLoop 阻塞读取消息:回 ACK,对同步包解密并回调 handler。
|
||||
// 非 JSON / 非同步包消息仅记录后跳过。返回 ctx 错误或致命读取错误。
|
||||
// ReceiveLoop 消费 readPump 分发的 Push。响应帧永远不会进入这里,因此不会被
|
||||
// 错误 ACK;Push ACK 原样复用服务端完整 headers。
|
||||
func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[string]any)) error {
|
||||
c.ensureReadPump()
|
||||
for {
|
||||
msgType, data, err := c.readNext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("WS read: %w", err)
|
||||
var frame incomingFrame
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-c.readDone:
|
||||
return fmt.Errorf("WS read: %w", c.connectionReadError())
|
||||
case frame = <-c.pushes:
|
||||
}
|
||||
_ = msgType
|
||||
rawText := string(data)
|
||||
var raw map[string]any
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
if c.recorder != nil {
|
||||
c.recorder("in", rawText, "", "non_json", err.Error())
|
||||
}
|
||||
c.logger.Debug("非 JSON 消息,跳过", "err", err)
|
||||
continue
|
||||
}
|
||||
if c.recorder != nil {
|
||||
if b, e := json.Marshal(raw); e == nil {
|
||||
c.recorder("in", rawText, string(b), "json", "")
|
||||
} else {
|
||||
c.recorder("in", rawText, "", "json", e.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// 心跳响应等直接跳过。
|
||||
if code, ok := raw["code"]; ok && code != nil {
|
||||
c.logger.Debug("收到响应", "code", code)
|
||||
}
|
||||
|
||||
// 收到消息后先回复 ACK。
|
||||
raw := frame.parsed
|
||||
rawText := string(frame.data)
|
||||
c.sendACK(ctx, raw)
|
||||
if err := c.handleSyncExtra(ctx, raw); err != nil {
|
||||
c.logger.Error("同步状态恢复失败", "err", err)
|
||||
}
|
||||
|
||||
// 仅处理同步包:body.syncPushPackage.data[0].data
|
||||
syncData, ok := extractSyncPayload(raw)
|
||||
@@ -383,21 +496,40 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
|
||||
}
|
||||
}
|
||||
|
||||
// sendACK 回复 {"code":200, headers:{mid,sid,...}},失败时仅记录日志。
|
||||
func (c *Conn) handleSyncExtra(ctx context.Context, msg map[string]any) error {
|
||||
body, _ := msg["body"].(map[string]any)
|
||||
extra, _ := body["syncExtraType"].(map[string]any)
|
||||
typeCode, ok := responseCode(extra["type"])
|
||||
if !ok || (typeCode != 1 && typeCode != 2) {
|
||||
return nil
|
||||
}
|
||||
state, err := c.request(ctx, "/r/SyncStatus/getState", map[string]any{}, []any{map[string]any{"topic": "sync"}}, regResponseTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("getState: %w", err)
|
||||
}
|
||||
if code, ok := responseCode(state["code"]); !ok || code != http.StatusOK || state["body"] == nil {
|
||||
return fmt.Errorf("getState 返回异常: code=%v", state["code"])
|
||||
}
|
||||
response, err := c.request(ctx, "/r/SyncStatus/ackDiff", map[string]any{}, []any{state["body"]}, regResponseTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ackDiff: %w", err)
|
||||
}
|
||||
if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
|
||||
return fmt.Errorf("ackDiff 返回异常: code=%d", code)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendACK 回复 {"code":200, headers:<服务端完整 headers>}。
|
||||
func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
|
||||
headers, _ := msg["headers"].(map[string]any)
|
||||
ack := map[string]any{
|
||||
"code": 200,
|
||||
"headers": map[string]any{
|
||||
"mid": ackVal(headers, "mid", protocol.GenerateMid()),
|
||||
"sid": ackVal(headers, "sid", ""),
|
||||
},
|
||||
ackHeaders := make(map[string]any, len(headers))
|
||||
for key, value := range headers {
|
||||
ackHeaders[key] = value
|
||||
}
|
||||
ackHeaders := ack["headers"].(map[string]any)
|
||||
for _, k := range []string{"app-key", "ua", "dt"} {
|
||||
if v, ok := headers[k]; ok && v != nil {
|
||||
ackHeaders[k] = v
|
||||
}
|
||||
ack := map[string]any{
|
||||
"code": 200,
|
||||
"headers": ackHeaders,
|
||||
}
|
||||
// ACK 失败不阻塞主循环。
|
||||
ackCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
@@ -405,14 +537,6 @@ func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
|
||||
cancel()
|
||||
}
|
||||
|
||||
// ackVal 取 header 中的 key,缺失或为 nil 时返回 fallback。
|
||||
func ackVal(headers map[string]any, key string, fallback any) any {
|
||||
if v, ok := headers[key]; ok && v != nil {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// extractSyncPayload 取出 body.syncPushPackage.data[0].data(字符串)。
|
||||
func extractSyncPayload(msg map[string]any) (string, bool) {
|
||||
body, _ := msg["body"].(map[string]any)
|
||||
@@ -561,5 +685,7 @@ func stripGoofish(s string) string {
|
||||
|
||||
// Close 关闭连接。
|
||||
func (c *Conn) Close() error {
|
||||
c.ensureReadPump()
|
||||
c.readCancel()
|
||||
return c.ws.Close(websocket.StatusNormalClosure, "bye")
|
||||
}
|
||||
@@ -2,15 +2,27 @@ package ws
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/xianyu"
|
||||
)
|
||||
|
||||
func TestWebsocketHeadersOnlyContainSanitizedCookie(t *testing.T) {
|
||||
got := websocketHeaders("a=1;\r\nb=2")
|
||||
want := map[string][]string{"Cookie": {"a=1;b=2"}}
|
||||
if !reflect.DeepEqual(map[string][]string(got), want) {
|
||||
t.Fatalf("websocket headers = %#v, want %#v", got, want)
|
||||
func TestWebsocketHeadersMatchBrowserHandshake(t *testing.T) {
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "runtime-browser-ua"})
|
||||
got := websocketHeaders()
|
||||
if got.Get("Origin") != "https://www.goofish.com" || got.Get("User-Agent") != "runtime-browser-ua" {
|
||||
t.Fatalf("websocket headers = %#v", got)
|
||||
}
|
||||
if got.Get("Cookie") != "" {
|
||||
t.Fatalf("dingtalk WebSocket 不应收到 goofish Cookie: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOfficialRegistrationUAUsesRuntimeBrowserVersion(t *testing.T) {
|
||||
raw := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/138.0.7204.92 Safari/537.36"
|
||||
want := raw + " DingTalk(2.2.0) OS(Mac OS/10.15.7) Browser(Chrome/138.0.7204.92) DingWeb/2.2.0 DingWeb/2.2.0"
|
||||
if got := OfficialRegistrationUA(raw); got != want {
|
||||
t.Fatalf("OfficialRegistrationUA() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,13 +52,6 @@ func TestDecodeSyncDataJSONAndInvalid(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWSHelpers(t *testing.T) {
|
||||
headers := map[string]any{"mid": "m1", "nil": nil}
|
||||
if got := ackVal(headers, "mid", "fallback"); got != "m1" {
|
||||
t.Fatalf("ackVal existing = %v", got)
|
||||
}
|
||||
if got := ackVal(headers, "nil", "fallback"); got != "fallback" {
|
||||
t.Fatalf("ackVal nil = %v", got)
|
||||
}
|
||||
if got := stripGoofish(" 123@goofish "); got != "123" {
|
||||
t.Fatalf("stripGoofish = %q", got)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -17,8 +16,7 @@ import (
|
||||
"xianyu-go/internal/xianyu"
|
||||
)
|
||||
|
||||
// startRegServer 启动一个本地 WS 服务,模拟 /reg 握手:读取客户端发来的 /reg 与
|
||||
// ackDiff 两条消息,验证它们的结构,然后保持连接打开(由调用方决定何时关闭)。
|
||||
// startRegServer 启动一个本地 WS 服务,模拟 /reg 握手并保持连接打开。
|
||||
// 返回服务实例与一个收集到所有客户端消息的 channel。
|
||||
func startRegServer(t *testing.T) (*httptest.Server, chan map[string]any) {
|
||||
t.Helper()
|
||||
@@ -75,13 +73,13 @@ func dialLocal(t *testing.T, srv *httptest.Server, cfg Config) *Conn {
|
||||
}
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
t.Cleanup(func() { _ = dialed.CloseNow() })
|
||||
return &Conn{ws: dialed, cfg: cfg, logger: nilLogger(), recorder: cfg.Recorder}
|
||||
return newConn(dialed, cfg, nilLogger())
|
||||
}
|
||||
|
||||
// TestRegister_SendsRegAndAckDiff 直接调用 register 覆盖 /reg 握手 + ackDiff 两条消息。
|
||||
// 验证:1) /reg 消息含正确 lwp/app-key/token/ua/did;2) ackDiff 消息 lwp 正确且 body 非空。
|
||||
func TestRegister_SendsRegAndAckDiff(t *testing.T) {
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "playwright-native-ua"})
|
||||
// TestRegisterSendsOnlyOfficialReg 验证注册只发送 /reg,不再伪造 ackDiff。
|
||||
func TestRegisterSendsOnlyOfficialReg(t *testing.T) {
|
||||
rawUA := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/138.0.7204.92 Safari/537.36"
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: rawUA})
|
||||
srv, got := startRegServer(t)
|
||||
conn := dialLocal(t, srv, Config{
|
||||
CookieStr: "cookie=1",
|
||||
@@ -103,15 +101,15 @@ collect:
|
||||
select {
|
||||
case m := <-got:
|
||||
msgs = append(msgs, m)
|
||||
if len(msgs) >= 2 {
|
||||
if len(msgs) >= 1 {
|
||||
break collect
|
||||
}
|
||||
case <-timer.C:
|
||||
break collect
|
||||
}
|
||||
}
|
||||
if len(msgs) < 2 {
|
||||
t.Fatalf("期望收到 2 条消息,实际 %d: %#v", len(msgs), msgs)
|
||||
if len(msgs) != 1 {
|
||||
t.Fatalf("期望只收到 /reg,实际 %d: %#v", len(msgs), msgs)
|
||||
}
|
||||
|
||||
reg := msgs[0]
|
||||
@@ -125,8 +123,8 @@ collect:
|
||||
if headers["token"] != "token-abc" {
|
||||
t.Errorf("/reg token = %v, 期望 token-abc", headers["token"])
|
||||
}
|
||||
if headers["ua"] != "playwright-native-ua" {
|
||||
t.Errorf("/reg ua = %v, 期望 Playwright 原生 UA", headers["ua"])
|
||||
if headers["ua"] != OfficialRegistrationUA(rawUA) {
|
||||
t.Errorf("/reg ua = %v, 期望官方复合 UA", headers["ua"])
|
||||
}
|
||||
if headers["did"] != "device-xyz" {
|
||||
t.Errorf("/reg did = %v, 期望 device-xyz", headers["did"])
|
||||
@@ -135,27 +133,23 @@ collect:
|
||||
t.Errorf("/reg mid 应为非空字符串, 实际 %v", headers["mid"])
|
||||
}
|
||||
|
||||
ackDiff := msgs[1]
|
||||
if ackDiff["lwp"] != "/r/SyncStatus/ackDiff" {
|
||||
t.Fatalf("第二条消息 lwp 应为 ackDiff, 实际 %v", ackDiff["lwp"])
|
||||
}
|
||||
body, _ := ackDiff["body"].([]any)
|
||||
if len(body) == 0 {
|
||||
t.Fatalf("ackDiff body 为空")
|
||||
}
|
||||
first, _ := body[0].(map[string]any)
|
||||
if first["pipeline"] != "sync" || first["channel"] != "sync" {
|
||||
t.Errorf("ackDiff body[0] 结构异常: %#v", first)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegister_ContextCancelledDuringWait register 在 1 秒等待期间 ctx 取消应返回 ctx.Err。
|
||||
// TestRegister_ContextCancelledDuringWait register 等不到响应时应服从 ctx 取消。
|
||||
func TestRegister_ContextCancelledDuringWait(t *testing.T) {
|
||||
srv, _ := startRegServer(t)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
c, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.CloseNow()
|
||||
_, _, _ = c.Read(r.Context())
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
conn := dialLocal(t, srv, Config{})
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
// 等到 /reg 发出、进入 1 秒等待后再取消。
|
||||
go func() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
cancel()
|
||||
@@ -219,7 +213,6 @@ func TestRegisterBuffersFrameBeforeResponse(t *testing.T) {
|
||||
_ = c.Write(ctx, websocket.MessageText, pushRaw)
|
||||
response, _ := json.Marshal(map[string]any{"code": 200, "headers": map[string]any{"mid": headers["mid"]}})
|
||||
_ = c.Write(ctx, websocket.MessageText, response)
|
||||
_, _, _ = c.Read(ctx) // ackDiff
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
@@ -229,12 +222,13 @@ func TestRegisterBuffersFrameBeforeResponse(t *testing.T) {
|
||||
if err := conn.register(ctx); err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
_, data, err := conn.readNext(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("read buffered frame: %v", err)
|
||||
}
|
||||
var got map[string]any
|
||||
_ = json.Unmarshal(data, &got)
|
||||
select {
|
||||
case frame := <-conn.pushes:
|
||||
got = frame.parsed
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("read buffered frame: %v", ctx.Err())
|
||||
}
|
||||
if got["lwp"] != push["lwp"] {
|
||||
t.Fatalf("buffered frame=%v want=%v", got, push)
|
||||
}
|
||||
@@ -266,7 +260,7 @@ func TestDial_RegisterFailure(t *testing.T) {
|
||||
}
|
||||
defer dialed.CloseNow()
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
conn := &Conn{ws: dialed, cfg: Config{}, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
err = conn.register(dialCtx)
|
||||
if err == nil {
|
||||
t.Fatal("register 应在连接关闭时返回错误")
|
||||
@@ -328,7 +322,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
|
||||
defer dialed.CloseNow()
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
|
||||
conn := &Conn{ws: dialed, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
var ackSeen map[string]any
|
||||
var onMessageCount int
|
||||
loopDone := make(chan error, 1)
|
||||
@@ -366,7 +360,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendACK_NoHeaders 消息无 headers 时 ACK 用 fallback mid(GenerateMid 非空)且 sid 为空。
|
||||
// TestSendACK_NoHeaders 消息无 headers 时 ACK 原样返回空 headers。
|
||||
func TestSendACK_NoHeaders(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
c, err := websocket.Accept(w, r, nil)
|
||||
@@ -408,7 +402,7 @@ func TestSendACK_NoHeaders(t *testing.T) {
|
||||
defer dialed.CloseNow()
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
|
||||
conn := &Conn{ws: dialed, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
var ackSeen map[string]any
|
||||
loopDone := make(chan error, 1)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
@@ -425,22 +419,13 @@ func TestSendACK_NoHeaders(t *testing.T) {
|
||||
t.Fatal("未收到 ack")
|
||||
}
|
||||
ackHeaders, _ := ackSeen["headers"].(map[string]any)
|
||||
mid, _ := ackHeaders["mid"].(string)
|
||||
if mid == "" {
|
||||
t.Errorf("无 headers 时 ACK mid 应用 fallback (GenerateMid), 实际空")
|
||||
}
|
||||
if ackHeaders["sid"] != "" {
|
||||
t.Errorf("无 headers 时 ACK sid 应为空, 实际 %v", ackHeaders["sid"])
|
||||
if len(ackHeaders) != 0 {
|
||||
t.Errorf("无 headers 时 ACK 应保持空 headers, 实际 %v", ackHeaders)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHeartbeatLoop_SendFailure 服务端立刻关闭连接,HeartbeatLoop 的 sendJSON 应失败;
|
||||
// 连续失败达 maxFailures(3) 次后应返回错误。
|
||||
// TestHeartbeatLoop_SendFailure 服务端关闭后心跳立即结束,不做三次写失败重试。
|
||||
func TestHeartbeatLoop_SendFailure(t *testing.T) {
|
||||
oldRetry := heartbeatRetryInterval
|
||||
heartbeatRetryInterval = 20 * time.Millisecond
|
||||
t.Cleanup(func() { heartbeatRetryInterval = oldRetry })
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
c, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
@@ -460,7 +445,7 @@ func TestHeartbeatLoop_SendFailure(t *testing.T) {
|
||||
defer dialed.CloseNow()
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
|
||||
conn := &Conn{ws: dialed, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
loopDone := make(chan error, 1)
|
||||
@@ -472,9 +457,6 @@ func TestHeartbeatLoop_SendFailure(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("HeartbeatLoop 应在连续失败后返回错误")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "心跳连续失败") {
|
||||
t.Fatalf("期望心跳连续失败错误, 实际 %v", err)
|
||||
}
|
||||
case <-time.After(8 * time.Second):
|
||||
t.Fatal("HeartbeatLoop 未在超时内退出")
|
||||
}
|
||||
@@ -759,7 +741,7 @@ func TestSetRecorder_RecordsOutgoingAndIncoming(t *testing.T) {
|
||||
dir, parsed, status string
|
||||
}{direction, parsedJSON, parseStatus})
|
||||
}
|
||||
conn := &Conn{ws: dialed, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
// 通过 SetRecorder 方法设置(覆盖该方法),而非直接赋值字段。
|
||||
conn.SetRecorder(rec)
|
||||
if conn.recorder == nil {
|
||||
@@ -825,7 +807,7 @@ func TestClose_TerminatesConnection(t *testing.T) {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
conn := &Conn{ws: dialed, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
|
||||
if err := conn.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
|
||||
@@ -66,7 +66,7 @@ func TestReceiveLoop_DecodesSyncPayload(t *testing.T) {
|
||||
defer dialed.CloseNow()
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
|
||||
conn := &Conn{ws: dialed, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
|
||||
var got map[string]any
|
||||
loopDone := make(chan error, 1)
|
||||
@@ -120,7 +120,7 @@ func TestReceiveLoop_NonJSONSkipped(t *testing.T) {
|
||||
defer dialed.CloseNow()
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
|
||||
conn := &Conn{ws: dialed, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
var got map[string]any
|
||||
loopDone := make(chan error, 1)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
@@ -162,7 +162,7 @@ func TestHeartbeatLoop_ContextCancel(t *testing.T) {
|
||||
defer dialed.CloseNow()
|
||||
dialed.SetReadLimit(8 << 20)
|
||||
|
||||
conn := &Conn{ws: dialed, logger: nilLogger()}
|
||||
conn := newConn(dialed, Config{}, nilLogger())
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
loopDone := make(chan error, 1)
|
||||
go func() {
|
||||
|
||||
Reference in new issue
Block a user