chore: 重构配套改动 + 包文档 + 构建产物清理
automation 重构期间的配套修改: - browser:订单抓取/密码登录/二维码刷新/stealth 等适配新流程,删 search.go - db:cookies/orders_ext/extras/sessions/users/password/repository 等调整 - xianyu:mtop client、protocol(sign/decrypt/msgpack/cookies)、qrlogin、ws、ua - server:admin/analytics/auth/cookie/helpers/item/item_publish_batch handlers - frontend:App/Dashboard/ItemList/Rules/Sidebar/api/types,删 Keywords/TestPage - auth、notify、webui、go.mod 等 本次会话补充: - cmd/server、cmd/init-admin 改为 // Package main 开头的标准包文档 - .gitignore 加 internal/webui/static/assets/(hash 化构建产物不入库) - internal/webui/static/index.html 重新构建 全量 go build/vet/test + race + 前端 test/build 通过。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
1 parent
3b4188c68c
commit
980de41b53
66 files changed
+3654
-2646
No files matched your search
@@ -25,6 +25,9 @@
|
||||
/frontend/.env.local
|
||||
/frontend/.env.*.local
|
||||
|
||||
# Frontend build artifacts (hash 化文件名,每次构建变化,不入库;index.html 与稳定 SVG 仍跟踪)
|
||||
/internal/webui/static/assets/
|
||||
|
||||
# OS / editor
|
||||
.DS_Store
|
||||
.idea/
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# 闲鱼管家
|
||||
|
||||
这是当前活跃版本:Go 后端 + React 前端。
|
||||
|
||||
旧目录 `../xianyu-super-butler/` 是历史 Python/FastAPI 版本。当前 `xianyu-go` 仓库已经包含自己的前端源码,后续功能迭代应改这里:
|
||||
这是当前活跃版本:Go 后端 + React 前端。后续功能迭代均在此目录进行:
|
||||
|
||||
```text
|
||||
xianyu-go/
|
||||
@@ -32,10 +30,10 @@ xianyu-go/internal/webui/static/
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go run ./cmd/server -init-admin -db data/xianyu_data.db
|
||||
go run ./cmd/init-admin -db data/xianyu_data.db
|
||||
```
|
||||
|
||||
也可以非交互传密码:
|
||||
也可以通过服务入口非交互初始化:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server \
|
||||
@@ -140,4 +138,3 @@ go test ./...
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend
|
||||
npm run build
|
||||
```
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// init-admin 交互式初始化管理员账号,移植自 Python init_admin.py。
|
||||
// Package main 交互式初始化管理员账号。
|
||||
// 沿用 Fork 安全基线:不创建默认口令,密码不回显、二次确认,bcrypt 哈希。
|
||||
//
|
||||
// 用法:go run ./cmd/init-admin -db data/xianyu_data.db
|
||||
|
||||
+4
-4
@@ -6,7 +6,7 @@ import OrderList from './components/OrderList';
|
||||
import CardList from './components/CardList';
|
||||
import ItemList from './components/ItemList';
|
||||
import Settings from './components/Settings';
|
||||
import Keywords from './components/Keywords';
|
||||
import Rules from './components/Rules';
|
||||
import { login, verifySession } from './services/api';
|
||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
||||
|
||||
@@ -96,7 +96,7 @@ const App: React.FC = () => {
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 rounded-2xl bg-gray-50 border border-gray-100">
|
||||
<div className="text-sm font-bold text-gray-900 mb-2">请在服务器上执行:</div>
|
||||
<pre className="text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto">python3 init_admin.py</pre>
|
||||
<pre className="text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto">./xianyu-server -init-admin -db data/xianyu_data.db -admin-password '请设置密码'</pre>
|
||||
<div className="text-xs text-gray-500 mt-2">完成后刷新页面即可进入登录。</div>
|
||||
</div>
|
||||
|
||||
@@ -196,9 +196,9 @@ const App: React.FC = () => {
|
||||
case 'cards': return <CardList />;
|
||||
case 'items': return <ItemList onConfigureDelivery={(item) => {
|
||||
setDeliveryRuleTarget({ cookieId: item.cookie_id, itemId: item.item_id, requestId: Date.now() });
|
||||
setActiveTab('keywords');
|
||||
setActiveTab('rules');
|
||||
}} />;
|
||||
case 'keywords': return <Keywords
|
||||
case 'rules': return <Rules
|
||||
initialDeliveryTarget={deliveryRuleTarget}
|
||||
onDeliveryTargetHandled={() => setDeliveryRuleTarget(undefined)}
|
||||
/>;
|
||||
|
||||
@@ -71,106 +71,60 @@ const Dashboard: React.FC = () => {
|
||||
// 颜色配置
|
||||
const COLORS = ['#0094f7', '#3B82F6', '#10B981', '#F59E0B', '#8B5CF6'];
|
||||
const formatCurrency = (value: number) => `¥${Number(value || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`;
|
||||
const formatLocalDate = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
|
||||
const getDatesForRange = (range: TimeRange) => {
|
||||
const now = new Date();
|
||||
const endDate = formatLocalDate(now);
|
||||
let startDate = endDate;
|
||||
|
||||
if (range === 'yesterday') {
|
||||
const yesterday = new Date(now);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
const yesterdayStr = formatLocalDate(yesterday);
|
||||
return { startDate: yesterdayStr, endDate: yesterdayStr };
|
||||
}
|
||||
if (range === '3days') {
|
||||
const threeDaysAgo = new Date(now);
|
||||
threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
|
||||
startDate = formatLocalDate(threeDaysAgo);
|
||||
} else if (range === '7days') {
|
||||
const sevenDaysAgo = new Date(now);
|
||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
|
||||
startDate = formatLocalDate(sevenDaysAgo);
|
||||
} else if (range === '30days') {
|
||||
const thirtyDaysAgo = new Date(now);
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
startDate = formatLocalDate(thirtyDaysAgo);
|
||||
} else if (range === 'custom' && customStartDate && customEndDate) {
|
||||
return { startDate: customStartDate, endDate: customEndDate };
|
||||
} else if (range === 'custom') {
|
||||
const sevenDaysAgo = new Date(now);
|
||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
|
||||
startDate = formatLocalDate(sevenDaysAgo);
|
||||
}
|
||||
|
||||
return { startDate, endDate };
|
||||
};
|
||||
|
||||
const loadValidOrders = (range: TimeRange) => {
|
||||
const { startDate, endDate } = getDatesForRange(range);
|
||||
setOrdersLoading(true);
|
||||
getValidOrders({ start_date: startDate, end_date: endDate })
|
||||
.then(setValidOrders)
|
||||
.catch(console.error)
|
||||
.finally(() => setOrdersLoading(false));
|
||||
};
|
||||
|
||||
const loadAnalytics = (range: TimeRange) => {
|
||||
// 使用本地时间而不是UTC时间
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getDate()).padStart(2, '0');
|
||||
const todayStr = `${year}-${month}-${day}`;
|
||||
|
||||
let params: { start_date: string; end_date: string };
|
||||
|
||||
switch (range) {
|
||||
case 'today':
|
||||
// 今天:从今天00:00:00到今天23:59:59
|
||||
params = {
|
||||
start_date: todayStr,
|
||||
end_date: todayStr
|
||||
};
|
||||
break;
|
||||
case 'yesterday':
|
||||
// 昨天:从昨天00:00:00到昨天23:59:59
|
||||
const yesterday = new Date(now);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
const yYear = yesterday.getFullYear();
|
||||
const yMonth = String(yesterday.getMonth() + 1).padStart(2, '0');
|
||||
const yDay = String(yesterday.getDate()).padStart(2, '0');
|
||||
const yesterdayStr = `${yYear}-${yMonth}-${yDay}`;
|
||||
params = {
|
||||
start_date: yesterdayStr,
|
||||
end_date: yesterdayStr
|
||||
};
|
||||
break;
|
||||
case '3days':
|
||||
// 3天:从3天前到今天
|
||||
const threeDaysAgo = new Date(now);
|
||||
threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
|
||||
const tdYear = threeDaysAgo.getFullYear();
|
||||
const tdMonth = String(threeDaysAgo.getMonth() + 1).padStart(2, '0');
|
||||
const tdDay = String(threeDaysAgo.getDate()).padStart(2, '0');
|
||||
params = {
|
||||
start_date: `${tdYear}-${tdMonth}-${tdDay}`,
|
||||
end_date: todayStr
|
||||
};
|
||||
break;
|
||||
case '7days':
|
||||
// 7天:从7天前到今天
|
||||
const sevenDaysAgo = new Date(now);
|
||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
|
||||
const sdYear = sevenDaysAgo.getFullYear();
|
||||
const sdMonth = String(sevenDaysAgo.getMonth() + 1).padStart(2, '0');
|
||||
const sdDay = String(sevenDaysAgo.getDate()).padStart(2, '0');
|
||||
params = {
|
||||
start_date: `${sdYear}-${sdMonth}-${sdDay}`,
|
||||
end_date: todayStr
|
||||
};
|
||||
break;
|
||||
case '30days':
|
||||
// 30天:从30天前到今天
|
||||
const thirtyDaysAgo = new Date(now);
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
const tdYear2 = thirtyDaysAgo.getFullYear();
|
||||
const tdMonth2 = String(thirtyDaysAgo.getMonth() + 1).padStart(2, '0');
|
||||
const tdDay2 = String(thirtyDaysAgo.getDate()).padStart(2, '0');
|
||||
params = {
|
||||
start_date: `${tdYear2}-${tdMonth2}-${tdDay2}`,
|
||||
end_date: todayStr
|
||||
};
|
||||
break;
|
||||
case 'custom':
|
||||
// 自定义范围
|
||||
if (customStartDate && customEndDate) {
|
||||
params = {
|
||||
start_date: customStartDate,
|
||||
end_date: customEndDate
|
||||
};
|
||||
} else {
|
||||
// 默认7天
|
||||
const defaultDaysAgo = new Date(now);
|
||||
defaultDaysAgo.setDate(defaultDaysAgo.getDate() - 7);
|
||||
const ddYear = defaultDaysAgo.getFullYear();
|
||||
const ddMonth = String(defaultDaysAgo.getMonth() + 1).padStart(2, '0');
|
||||
const ddDay = String(defaultDaysAgo.getDate()).padStart(2, '0');
|
||||
params = {
|
||||
start_date: `${ddYear}-${ddMonth}-${ddDay}`,
|
||||
end_date: todayStr
|
||||
};
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// 默认7天
|
||||
const defaultStart = new Date(now);
|
||||
defaultStart.setDate(defaultStart.getDate() - 7);
|
||||
const dsYear = defaultStart.getFullYear();
|
||||
const dsMonth = String(defaultStart.getMonth() + 1).padStart(2, '0');
|
||||
const dsDay = String(defaultStart.getDate()).padStart(2, '0');
|
||||
params = {
|
||||
start_date: `${dsYear}-${dsMonth}-${dsDay}`,
|
||||
end_date: todayStr
|
||||
};
|
||||
}
|
||||
const { startDate, endDate } = getDatesForRange(range);
|
||||
const params = { start_date: startDate, end_date: endDate };
|
||||
|
||||
// 同时获取上一个周期的数据用于趋势对比
|
||||
const previousParams = getPreviousPeriodParams(range, now);
|
||||
@@ -268,38 +222,9 @@ const Dashboard: React.FC = () => {
|
||||
|
||||
// 加载订单列表
|
||||
useEffect(() => {
|
||||
const { startDate, endDate } = getDatesForRange(timeRange);
|
||||
|
||||
// 获取参与统计的订单列表
|
||||
setOrdersLoading(true);
|
||||
getValidOrders({ start_date: startDate, end_date: endDate })
|
||||
.then(orders => {
|
||||
setValidOrders(orders);
|
||||
})
|
||||
.catch(console.error)
|
||||
.finally(() => setOrdersLoading(false));
|
||||
loadValidOrders(timeRange);
|
||||
}, [timeRange]);
|
||||
|
||||
// 辅助函数:获取时间范围的日期
|
||||
const getDatesForRange = (range: TimeRange) => {
|
||||
const now = new Date();
|
||||
const endDate = now.toISOString().split('T')[0];
|
||||
let startDate = endDate;
|
||||
|
||||
if (range === '7days') {
|
||||
const sevenDaysAgo = new Date(now);
|
||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
|
||||
startDate = sevenDaysAgo.toISOString().split('T')[0];
|
||||
} else if (range === '30days') {
|
||||
const thirtyDaysAgo = new Date(now);
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
startDate = thirtyDaysAgo.toISOString().split('T')[0];
|
||||
}
|
||||
// 其他范围类似处理...
|
||||
|
||||
return { startDate, endDate };
|
||||
};
|
||||
|
||||
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-[#0094f7]" /></div>;
|
||||
|
||||
const chartData = analytics.daily_stats?.map(d => ({
|
||||
@@ -371,6 +296,14 @@ const Dashboard: React.FC = () => {
|
||||
{ key: 'custom' as TimeRange, label: '自定义' },
|
||||
];
|
||||
const selectedRangeLabel = timeRangeOptions.find(option => option.key === timeRange)?.label || '所选范围';
|
||||
const currentRangeDates = getDatesForRange(timeRange);
|
||||
const normalizedSearchTerm = searchTerm.trim().toLowerCase();
|
||||
const filteredValidOrders = validOrders.filter((order) =>
|
||||
order.order_id?.toLowerCase().includes(normalizedSearchTerm) ||
|
||||
order.item_id?.toLowerCase().includes(normalizedSearchTerm) ||
|
||||
order.item_title?.toLowerCase().includes(normalizedSearchTerm) ||
|
||||
order.buyer_id?.toLowerCase().includes(normalizedSearchTerm)
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-fade-in">
|
||||
@@ -418,7 +351,10 @@ const Dashboard: React.FC = () => {
|
||||
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"
|
||||
/>
|
||||
<button
|
||||
onClick={() => loadAnalytics('custom')}
|
||||
onClick={() => {
|
||||
loadAnalytics('custom');
|
||||
loadValidOrders('custom');
|
||||
}}
|
||||
className="px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors"
|
||||
>
|
||||
应用
|
||||
@@ -643,13 +579,28 @@ const Dashboard: React.FC = () => {
|
||||
<Activity className="w-6 h-6 animate-spin mr-2" />
|
||||
加载中...
|
||||
</div>
|
||||
) : validOrders.filter((order) =>
|
||||
order.order_id?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
order.item_id?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
order.buyer_id?.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
).length === 0 ? (
|
||||
<div className="flex items-center justify-center py-20 text-gray-400">
|
||||
暂无订单数据
|
||||
) : filteredValidOrders.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-16 px-8 text-center">
|
||||
<div className="w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4">
|
||||
<PackageCheck className="w-7 h-7 text-gray-300" />
|
||||
</div>
|
||||
{normalizedSearchTerm ? (
|
||||
<>
|
||||
<div className="text-sm font-extrabold text-gray-900">没有匹配的订单</div>
|
||||
<div className="text-xs text-gray-400 mt-2 max-w-md">
|
||||
当前共有 {validOrders.length} 单参与统计,但没有订单号、商品、买家匹配“{searchTerm}”。
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-sm font-extrabold text-gray-900">当前范围内没有参与统计的订单</div>
|
||||
<div className="text-xs text-gray-400 mt-2 max-w-lg leading-6">
|
||||
日期范围:{currentRangeDates.startDate} 至 {currentRangeDates.endDate};
|
||||
统计口径:待发货、已发货、已完成,且订单金额不为空。
|
||||
当前统计卡片订单数:{analytics.revenue_stats.total_orders} 单。
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<table className="w-full text-left border-collapse">
|
||||
@@ -663,13 +614,7 @@ const Dashboard: React.FC = () => {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-50">
|
||||
{validOrders
|
||||
.filter((order) =>
|
||||
order.order_id?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
order.item_id?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
order.buyer_id?.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
)
|
||||
.map((order) => (
|
||||
{filteredValidOrders.map((order) => (
|
||||
<tr key={order.order_id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
|
||||
<td className="px-6 py-4">
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -14,11 +14,9 @@ import {
|
||||
retryFailedItemPublishBatch,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
setItemMultiSpec,
|
||||
setItemMultiQuantity,
|
||||
getShippingRules
|
||||
} from '../services/api';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, CopyPlus, Edit, Layers3, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, X } from 'lucide-react';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, X } from 'lucide-react';
|
||||
|
||||
interface ItemListProps {
|
||||
onConfigureDelivery: (item: Item) => void;
|
||||
@@ -35,9 +33,6 @@ interface PublishBatchPreviewRow {
|
||||
price: string;
|
||||
quantity: number;
|
||||
images: string[];
|
||||
auto_create_delivery_rule: boolean;
|
||||
card_group_id: number;
|
||||
delivery_count: number;
|
||||
}
|
||||
|
||||
interface PublishBatchDetailRow {
|
||||
@@ -47,9 +42,6 @@ interface PublishBatchDetailRow {
|
||||
title: string;
|
||||
price: string;
|
||||
quantity: number;
|
||||
auto_create_delivery_rule: boolean;
|
||||
card_group_id: number;
|
||||
delivery_count: number;
|
||||
status: string;
|
||||
item_id: string;
|
||||
item_url: string;
|
||||
@@ -69,6 +61,12 @@ interface PublishBatchDetail {
|
||||
rows: PublishBatchDetailRow[];
|
||||
}
|
||||
|
||||
const formatItemPrice = (price?: string) => {
|
||||
const value = String(price || '').trim();
|
||||
if (!value) return '-';
|
||||
return /^[¥¥]/.test(value) ? value : `¥${value}`;
|
||||
};
|
||||
|
||||
const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [shippingRules, setShippingRules] = useState<ShippingRule[]>([]);
|
||||
@@ -99,9 +97,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
item_id: '',
|
||||
item_title: '',
|
||||
item_price: '',
|
||||
item_image: '',
|
||||
is_multi_spec: false,
|
||||
is_multi_qty_ship: false
|
||||
item_image: ''
|
||||
});
|
||||
const [publishForm, setPublishForm] = useState({
|
||||
cookie_id: '',
|
||||
@@ -182,8 +178,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
item_category: editForm.item_category || '',
|
||||
item_price: editForm.item_price || '',
|
||||
item_detail: editForm.item_detail || selectedItem.item_detail || '',
|
||||
is_multi_spec: Boolean(editForm.is_multi_spec),
|
||||
multi_quantity_delivery: Boolean(editForm.is_multi_qty_ship ?? editForm.multi_quantity_delivery),
|
||||
});
|
||||
await loadItems();
|
||||
await loadShippingRules();
|
||||
@@ -218,8 +212,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
item_title: addForm.item_title,
|
||||
item_price: addForm.item_price,
|
||||
item_detail: addForm.item_image ? JSON.stringify({ item_image: addForm.item_image }) : '',
|
||||
is_multi_spec: addForm.is_multi_spec,
|
||||
is_multi_qty_ship: addForm.is_multi_qty_ship,
|
||||
});
|
||||
await loadItems();
|
||||
setShowAddModal(false);
|
||||
@@ -228,9 +220,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
item_id: '',
|
||||
item_title: '',
|
||||
item_price: '',
|
||||
item_image: '',
|
||||
is_multi_spec: false,
|
||||
is_multi_qty_ship: false
|
||||
item_image: ''
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('添加商品失败:', error);
|
||||
@@ -366,10 +356,14 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
};
|
||||
|
||||
const downloadPublishTemplate = () => {
|
||||
const headers = ['账号ID', '标题', '描述', '价格', '原价', '库存', '邮费模式', '邮费', '图片', '自动创建发货规则', '卡密组ID', '发货数量'];
|
||||
const headers = [
|
||||
'账号ID', '标题', '描述', '价格', '原价', '库存', '邮费模式', '邮费', '图片',
|
||||
'付款后自动发货', '付款后发送的卡密', '评价后发送赠品', '评价后发送的卡密',
|
||||
'超时未评价时提醒', '发货几小时后提醒', '提醒内容', '最多提醒几次',
|
||||
];
|
||||
const rows = [
|
||||
['', '会员月卡自动发货', '下单后自动发货,请按说明使用。', '19.90', '29.90', '10', 'free', '', 'images/month-card-1.jpg;images/month-card-2.jpg', '是', '请填写卡密页看到的ID', '1'],
|
||||
['', '会员季卡自动发货', '支持自动发货。', '49.90', '', '10', 'fixed', '8.00', 'https://example.com/product.jpg', '否', '', '1'],
|
||||
['', '会员组合包自动发货', '下单后发送主卡和附赠卡。', '19.90', '29.90', '10', 'free', '', 'images/bundle-1.jpg;images/bundle-2.jpg', '是', '101:1;102:1', '是', '201:1;202:2', '是', '72', '亲,满意的话麻烦给个评价,谢谢~', '1'],
|
||||
['', '普通商品', '仅发布商品,不创建自动化规则。', '49.90', '', '10', 'fixed', '8.00', 'https://example.com/product.jpg', '否', '', '否', '', '否', '', '', ''],
|
||||
];
|
||||
const csv = [headers, ...rows]
|
||||
.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
|
||||
@@ -385,36 +379,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const toggleMultiSpec = async (item: Item) => {
|
||||
const next = !Boolean(item.is_multi_spec);
|
||||
setItems(prev => prev.map(i =>
|
||||
i.cookie_id === item.cookie_id && i.item_id === item.item_id
|
||||
? { ...i, is_multi_spec: next }
|
||||
: i
|
||||
));
|
||||
try {
|
||||
await setItemMultiSpec(item.cookie_id, item.item_id, next);
|
||||
} catch (error) {
|
||||
console.error('切换状态失败:', error);
|
||||
await loadItems();
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMultiQty = async (item: Item) => {
|
||||
const next = !Boolean(item.is_multi_qty_ship);
|
||||
setItems(prev => prev.map(i =>
|
||||
i.cookie_id === item.cookie_id && i.item_id === item.item_id
|
||||
? { ...i, is_multi_qty_ship: next, multi_quantity_delivery: next }
|
||||
: i
|
||||
));
|
||||
try {
|
||||
await setItemMultiQuantity(item.cookie_id, item.item_id, next);
|
||||
} catch (error) {
|
||||
console.error('切换状态失败:', error);
|
||||
await loadItems();
|
||||
}
|
||||
};
|
||||
|
||||
const openAddModal = () => {
|
||||
setAddForm(prev => ({ ...prev, cookie_id: selectedAccount || prev.cookie_id }));
|
||||
setShowAddModal(true);
|
||||
@@ -508,23 +472,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<div className="bg-white border border-blue-100 rounded-2xl p-5 flex items-start gap-4 shadow-sm">
|
||||
<div className="w-10 h-10 rounded-xl bg-blue-50 text-[#0094f7] flex items-center justify-center shrink-0"><Layers3 className="w-5 h-5" /></div>
|
||||
<div>
|
||||
<div className="font-extrabold text-gray-900">多规格:按买家选择匹配库存</div>
|
||||
<p className="text-sm text-gray-500 mt-1 leading-6">开启后,在发货规则中配置“规格名称 + 规格值 → 卡密库存”,例如套餐 / 30天。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border border-emerald-100 rounded-2xl p-5 flex items-start gap-4 shadow-sm">
|
||||
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0"><CopyPlus className="w-5 h-5" /></div>
|
||||
<div>
|
||||
<div className="font-extrabold text-gray-900">按购买数量发货:自动倍增份数</div>
|
||||
<p className="text-sm text-gray-500 mt-1 leading-6">开启后,买家购买 3 件就执行规则 3 次;规则中的“每件份数”会继续相乘。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
|
||||
{items.map(item => {
|
||||
const linkedRules = rulesForItem(item);
|
||||
@@ -556,7 +503,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute top-2 left-2 bg-black/50 backdrop-blur-md text-white text-xs font-bold px-2 py-1 rounded-lg">
|
||||
¥{item.item_price}
|
||||
{formatItemPrice(item.item_price)}
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="font-bold text-gray-900 line-clamp-2 text-sm mb-2 h-10">{item.item_title}</h3>
|
||||
@@ -568,30 +515,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-2 mt-auto">
|
||||
<button
|
||||
onClick={() => toggleMultiSpec(item)}
|
||||
aria-pressed={Boolean(item.is_multi_spec)}
|
||||
className={`w-full text-left flex items-center justify-between gap-3 px-3 py-2.5 rounded-xl transition-colors border ${
|
||||
item.is_multi_spec
|
||||
? 'bg-blue-50 text-blue-700 border-blue-200'
|
||||
: 'bg-gray-50 text-gray-600 border-gray-100 hover:border-gray-200'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-2"><Layers3 className="w-4 h-4" /><span><span className="block text-xs font-extrabold">多规格匹配</span><span className="block text-[11px] font-medium opacity-70 mt-0.5">按订单规格选择库存</span></span></span>
|
||||
<span className={`text-[10px] font-extrabold px-2 py-1 rounded-full ${item.is_multi_spec ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-500'}`}>{item.is_multi_spec ? '已开启' : '关闭'}</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => toggleMultiQty(item)}
|
||||
aria-pressed={Boolean(item.is_multi_qty_ship)}
|
||||
className={`w-full text-left flex items-center justify-between gap-3 px-3 py-2.5 rounded-xl transition-colors border ${
|
||||
item.is_multi_qty_ship
|
||||
? 'bg-emerald-50 text-emerald-700 border-emerald-200'
|
||||
: 'bg-gray-50 text-gray-600 border-gray-100 hover:border-gray-200'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-2"><CopyPlus className="w-4 h-4" /><span><span className="block text-xs font-extrabold">按购买数量发货</span><span className="block text-[11px] font-medium opacity-70 mt-0.5">购买几件就执行几次</span></span></span>
|
||||
<span className={`text-[10px] font-extrabold px-2 py-1 rounded-full ${item.is_multi_qty_ship ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-500'}`}>{item.is_multi_qty_ship ? '已开启' : '关闭'}</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onConfigureDelivery(item)}
|
||||
className={`w-full flex items-center justify-between gap-2 px-3 py-2.5 rounded-xl text-xs font-extrabold transition-all ${hasRule ? 'bg-gray-900 text-white hover:bg-black' : 'bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100'}`}
|
||||
@@ -628,16 +551,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="价格" value={editForm.item_price || ''} onChange={e => setEditForm({...editForm, item_price: e.target.value})} />
|
||||
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="分类" value={editForm.item_category || ''} onChange={e => setEditForm({...editForm, item_category: e.target.value})} />
|
||||
<textarea className="w-full ios-input px-4 py-3 rounded-xl h-28 resize-none" placeholder="描述" value={editForm.item_description || ''} onChange={e => setEditForm({...editForm, item_description: e.target.value})} />
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700">
|
||||
<input type="checkbox" checked={Boolean(editForm.is_multi_spec)} onChange={e => setEditForm({...editForm, is_multi_spec: e.target.checked})} />
|
||||
多规格
|
||||
</label>
|
||||
<label className="flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700">
|
||||
<input type="checkbox" checked={Boolean(editForm.is_multi_qty_ship ?? editForm.multi_quantity_delivery)} onChange={e => setEditForm({...editForm, is_multi_qty_ship: e.target.checked})} />
|
||||
多数量发货
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button onClick={handleSaveEdit} className="w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2">
|
||||
@@ -687,16 +600,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<label className="block text-sm font-bold text-gray-700">图片 URL</label>
|
||||
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="https://..." value={addForm.item_image} onChange={e => setAddForm({...addForm, item_image: e.target.value})} />
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<label className="flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700">
|
||||
<input type="checkbox" checked={addForm.is_multi_spec} onChange={e => setAddForm({...addForm, is_multi_spec: e.target.checked})} />
|
||||
多规格
|
||||
</label>
|
||||
<label className="flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700">
|
||||
<input type="checkbox" checked={addForm.is_multi_qty_ship} onChange={e => setAddForm({...addForm, is_multi_qty_ship: e.target.checked})} />
|
||||
多数量发货
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button onClick={handleAddItem} className="w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
|
||||
@@ -891,35 +794,61 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<div className="rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3">
|
||||
<div>
|
||||
<div className="text-sm font-extrabold text-gray-900">字段说明</div>
|
||||
<p className="text-xs text-gray-500 mt-1">必填字段缺失会在预检阶段拦截,不会发布。</p>
|
||||
<p className="text-xs text-gray-500 mt-1">照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950">
|
||||
<div className="text-sm font-extrabold">“付款后发送的卡密”怎么填</div>
|
||||
<div className="mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3">
|
||||
<div className="rounded-lg bg-white/80 p-3">
|
||||
<code className="font-bold text-blue-700">101</code>
|
||||
<p className="mt-1 leading-5">从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。</p>
|
||||
</div>
|
||||
<div className="rounded-lg bg-white/80 p-3">
|
||||
<code className="font-bold text-blue-700">101:2</code>
|
||||
<p className="mt-1 leading-5">每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。</p>
|
||||
</div>
|
||||
<div className="rounded-lg bg-white/80 p-3">
|
||||
<code className="font-bold text-blue-700">101:1:0;102:2:3</code>
|
||||
<p className="mt-1 leading-5">先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-3 leading-5 text-blue-800">
|
||||
每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 <code className="font-bold">;</code> 隔开。
|
||||
</p>
|
||||
</div>
|
||||
<div className="overflow-x-auto rounded-xl border border-gray-100 bg-white">
|
||||
<table className="w-full text-left text-xs">
|
||||
<thead className="bg-gray-50 text-gray-500">
|
||||
<tr>
|
||||
<th className="px-3 py-2">字段</th>
|
||||
<th className="px-3 py-2">是否必填</th>
|
||||
<th className="px-3 py-2">说明</th>
|
||||
<th className="px-3 py-2">什么时候填写</th>
|
||||
<th className="px-3 py-2">填写方法</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-50 text-gray-700">
|
||||
{[
|
||||
['账号ID', '可空', '空时使用上方选择的默认发布账号'],
|
||||
['标题', '必填', '商品标题'],
|
||||
['描述', '可空', '空时默认等于标题'],
|
||||
['价格', '必填', '售价,例如 19.90'],
|
||||
['原价', '可空', '展示原价,例如 29.90'],
|
||||
['库存', '可空', '默认 1,必须大于 0'],
|
||||
['邮费模式', '可空', '默认 free;支持 free / fixed'],
|
||||
['邮费', '条件必填', '邮费模式 fixed 时填写,例如 8.00'],
|
||||
['图片', '必填', 'zip 内相对路径或 URL,多张用英文分号分隔'],
|
||||
['自动创建发货规则', '可空', '填 是/true/1 表示发布成功后创建自动发货规则'],
|
||||
['卡密组ID', '条件必填', '自动创建发货规则=是 时必填;在“卡密库存”页复制'],
|
||||
['发货数量', '可空', '默认 1,每个订单发送几份卡密'],
|
||||
].map(([name, required, desc]) => (
|
||||
['账号ID', '没有在上方选择默认账号时填写', '填写账号 ID;已经选择默认账号时可以留空'],
|
||||
['标题', '每个商品都要填', '填写买家能看到的商品标题'],
|
||||
['描述', '可以留空', '留空时会使用商品标题作为描述'],
|
||||
['价格', '每个商品都要填', '只填数字,例如 19.90'],
|
||||
['原价', '可以留空', '需要展示划线原价时填写,例如 29.90'],
|
||||
['库存', '可以留空', '留空按 1 件处理;填写时必须大于 0'],
|
||||
['邮费模式', '可以留空', '留空表示包邮;包邮填 free,固定邮费填 fixed'],
|
||||
['邮费', '邮费模式填 fixed 时填写', '只填数字,例如 8.00'],
|
||||
['图片', '每个商品都要填', '填写 zip 内图片路径或图片网址;多张图片用英文分号隔开'],
|
||||
['付款后自动发货', '需要付款后自动发货时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['付款后发送的卡密', '“付款后自动发货”填“是”时填写', '从“卡密库存”页面取得卡密组 ID,按上方示例填写'],
|
||||
['评价后发送赠品', '需要评价赠品时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['评价后发送的卡密', '“评价后发送赠品”填“是”时填写', '格式和付款后发送的卡密相同,也可以同时发送多个卡密组'],
|
||||
['超时未评价时提醒', '需要自动求评价时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['发货几小时后提醒', '“超时未评价时提醒”填“是”时填写', '填写等待小时数;留空按 72 小时处理'],
|
||||
['提醒内容', '“超时未评价时提醒”填“是”时填写', '填写要发送给买家的求评价消息'],
|
||||
['最多提醒几次', '可以留空', '留空只提醒 1 次'],
|
||||
].map(([name, when, desc]) => (
|
||||
<tr key={name}>
|
||||
<td className="px-3 py-2 font-bold text-gray-900 whitespace-nowrap">{name}</td>
|
||||
<td className={`px-3 py-2 whitespace-nowrap font-bold ${required === '必填' || required === '条件必填' ? 'text-red-600' : 'text-gray-500'}`}>{required}</td>
|
||||
<td className={`px-3 py-2 min-w-[210px] font-bold ${when === '每个商品都要填' ? 'text-red-600' : when === '可以留空' ? 'text-gray-500' : 'text-amber-700'}`}>{when}</td>
|
||||
<td className="px-3 py-2 min-w-[260px]">{desc}</td>
|
||||
</tr>
|
||||
))}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+1367
-370
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap, MessageSquare } from 'lucide-react';
|
||||
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap } from 'lucide-react';
|
||||
|
||||
interface SidebarProps {
|
||||
activeTab: string;
|
||||
@@ -14,7 +14,7 @@ const Sidebar: React.FC<SidebarProps> = ({ activeTab, setActiveTab, onLogout })
|
||||
{ id: 'orders', icon: ShoppingBag, label: '订单管理' },
|
||||
{ id: 'cards', icon: CreditCard, label: '卡密库存' },
|
||||
{ id: 'items', icon: Box, label: '商品列表' },
|
||||
{ id: 'keywords', icon: MessageSquare, label: '自动化规则' },
|
||||
{ id: 'rules', icon: Zap, label: '自动化规则' },
|
||||
{ id: 'settings', icon: Settings, label: '系统与AI' },
|
||||
];
|
||||
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
const TestPage: React.FC = () => {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
|
||||
<div className="bg-white p-8 rounded-2xl shadow-lg">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-4">测试页面</h1>
|
||||
<p className="text-gray-600 mb-4">如果你能看到这个页面,说明基础功能正常。</p>
|
||||
<div className="space-y-2">
|
||||
<div className="p-4 bg-blue-100 rounded-lg text-blue-800">蓝色卡片</div>
|
||||
<div className="p-4 bg-green-100 rounded-lg text-green-800">绿色卡片</div>
|
||||
<div className="p-4 bg-blue-100 rounded-lg text-blue-800">黄色卡片</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TestPage;
|
||||
Generated
+379
-1
@@ -21,7 +21,8 @@
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "~5.8.2",
|
||||
"vite": "^6.2.0"
|
||||
"vite": "^6.2.0",
|
||||
"vitest": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/@alloc/quick-lru": {
|
||||
@@ -1338,6 +1339,17 @@
|
||||
"@babel/types": "^7.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/chai": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
|
||||
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/deep-eql": "*",
|
||||
"assertion-error": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-array": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
|
||||
@@ -1401,6 +1413,13 @@
|
||||
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/deep-eql": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/estree": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
|
||||
@@ -1445,6 +1464,119 @@
|
||||
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/expect": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
"integrity": "sha512-7EHDquPthALSV0jhhjgEW8FXaviMx7rSqu8W6oqCoAuOhKov814P99QDV1pxMA3QPv21YudvJngIhjrNI4opLg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.1.0",
|
||||
"@types/chai": "^5.2.2",
|
||||
"@vitest/spy": "4.1.6",
|
||||
"@vitest/utils": "4.1.6",
|
||||
"chai": "^6.2.2",
|
||||
"tinyrainbow": "^3.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/mocker": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.6.tgz",
|
||||
"integrity": "sha512-MCFc63czMjEInOlcY2cpQCvCN+KgbAn+60xu9cMgP4sKaLC5JNAKw7JH8QdAnoAC88hW1IiSNZ+GgVXlN1UcMQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/spy": "4.1.6",
|
||||
"estree-walker": "^3.0.3",
|
||||
"magic-string": "^0.30.21"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"msw": "^2.4.9",
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"msw": {
|
||||
"optional": true
|
||||
},
|
||||
"vite": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/pretty-format": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.6.tgz",
|
||||
"integrity": "sha512-h5SxD/IzNhZYnrSZRsUZQIC+vD0GY8cUvq0iwsmkFKixRCKLLWqCXa/FIQ4S1R+sI+PGoojkHsdNrbZiM9Qpgw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tinyrainbow": "^3.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/runner": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.6.tgz",
|
||||
"integrity": "sha512-nOPCmn2+yD0ZNmKdsXGv/UxMMWbMuKeD6GyYncNwdkYDxpQvrPSKYj2rWuDjC2Y4b6w6hjip5dBKFzEUuZe3vA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/utils": "4.1.6",
|
||||
"pathe": "^2.0.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/snapshot": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.6.tgz",
|
||||
"integrity": "sha512-YhsdE6xAVfTDmzjxL2ZDUvjj+ZsgyOKe+TdQzqkD72wIOmHka8NuGQ6NpTNZv9D2Z63fbwWKJPeVpEw4EQgYxw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/pretty-format": "4.1.6",
|
||||
"@vitest/utils": "4.1.6",
|
||||
"magic-string": "^0.30.21",
|
||||
"pathe": "^2.0.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/spy": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.6.tgz",
|
||||
"integrity": "sha512-JFKxMx6udhwKh/Ldo270e17QX710vgunMkuPAvXjHSvC6oqLWAHhVhjg/I71q0u0CBSErIODV1Kjv0FQNSWjdg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/utils": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.6.tgz",
|
||||
"integrity": "sha512-FxIY+U81R3LGKCxaHHFRQ5+g6/iRgGLmeHWdp2Amj4ljQRrEIWHmZyDfDYBRZlpyqA7qKxtS9DD1dhk8RnRIVQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/pretty-format": "4.1.6",
|
||||
"convert-source-map": "^2.0.0",
|
||||
"tinyrainbow": "^3.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
|
||||
@@ -1485,6 +1617,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/assertion-error": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
|
||||
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
@@ -1657,6 +1799,16 @@
|
||||
],
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/chai": {
|
||||
"version": "6.2.2",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
|
||||
"integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
@@ -1952,6 +2104,13 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-module-lexer": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz",
|
||||
"integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/es-object-atoms": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
|
||||
@@ -2041,12 +2200,32 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/estree-walker": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
|
||||
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/estree": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eventemitter3": {
|
||||
"version": "5.0.4",
|
||||
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
|
||||
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/expect-type": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
|
||||
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-glob": {
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
||||
@@ -2461,6 +2640,16 @@
|
||||
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.21",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
|
||||
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
@@ -2592,6 +2781,20 @@
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/obug": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/obug/-/obug-2.1.3.tgz",
|
||||
"integrity": "sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
"https://github.com/sponsors/sxzz",
|
||||
"https://opencollective.com/debug"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/path-parse": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
|
||||
@@ -2599,6 +2802,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pathe": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
|
||||
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -3085,6 +3295,13 @@
|
||||
"semver": "bin/semver.js"
|
||||
}
|
||||
},
|
||||
"node_modules/siginfo": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
|
||||
"integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
@@ -3095,6 +3312,20 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/stackback": {
|
||||
"version": "0.0.2",
|
||||
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
|
||||
"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/std-env": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz",
|
||||
"integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/sucrase": {
|
||||
"version": "3.35.1",
|
||||
"resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz",
|
||||
@@ -3198,6 +3429,23 @@
|
||||
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
|
||||
"integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinyexec": {
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz",
|
||||
"integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.17",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
||||
@@ -3246,6 +3494,16 @@
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyrainbow": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",
|
||||
"integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/to-regex-range": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||
@@ -3462,6 +3720,126 @@
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/vitest": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.6.tgz",
|
||||
"integrity": "sha512-6lvjbS3p9b4CrdCmguzbh2/4uoXhGE2q71R4OX5sqF9R1bo9Xd6fGrMAfvp5wnCzlBnFVdCOp6onuTQVbo8iUQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/expect": "4.1.6",
|
||||
"@vitest/mocker": "4.1.6",
|
||||
"@vitest/pretty-format": "4.1.6",
|
||||
"@vitest/runner": "4.1.6",
|
||||
"@vitest/snapshot": "4.1.6",
|
||||
"@vitest/spy": "4.1.6",
|
||||
"@vitest/utils": "4.1.6",
|
||||
"es-module-lexer": "^2.0.0",
|
||||
"expect-type": "^1.3.0",
|
||||
"magic-string": "^0.30.21",
|
||||
"obug": "^2.1.1",
|
||||
"pathe": "^2.0.3",
|
||||
"picomatch": "^4.0.3",
|
||||
"std-env": "^4.0.0-rc.1",
|
||||
"tinybench": "^2.9.0",
|
||||
"tinyexec": "^1.0.2",
|
||||
"tinyglobby": "^0.2.15",
|
||||
"tinyrainbow": "^3.1.0",
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
|
||||
"why-is-node-running": "^2.3.0"
|
||||
},
|
||||
"bin": {
|
||||
"vitest": "vitest.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@edge-runtime/vm": "*",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
|
||||
"@vitest/browser-playwright": "4.1.6",
|
||||
"@vitest/browser-preview": "4.1.6",
|
||||
"@vitest/browser-webdriverio": "4.1.6",
|
||||
"@vitest/coverage-istanbul": "4.1.6",
|
||||
"@vitest/coverage-v8": "4.1.6",
|
||||
"@vitest/ui": "4.1.6",
|
||||
"happy-dom": "*",
|
||||
"jsdom": "*",
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@edge-runtime/vm": {
|
||||
"optional": true
|
||||
},
|
||||
"@opentelemetry/api": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-playwright": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-preview": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-webdriverio": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/coverage-istanbul": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/coverage-v8": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/ui": {
|
||||
"optional": true
|
||||
},
|
||||
"happy-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"jsdom": {
|
||||
"optional": true
|
||||
},
|
||||
"vite": {
|
||||
"optional": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vitest/node_modules/picomatch": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
|
||||
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/why-is-node-running": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
||||
"integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"siginfo": "^2.0.0",
|
||||
"stackback": "0.0.2"
|
||||
},
|
||||
"bin": {
|
||||
"why-is-node-running": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"test": "vitest run",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -22,6 +23,7 @@
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "~5.8.2",
|
||||
"vite": "^6.2.0"
|
||||
"vite": "^6.2.0",
|
||||
"vitest": "^4.1.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { get, post, postForm } from './request';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('request helpers', () => {
|
||||
test('encodes query parameters and includes credentials', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/items', { page: 2, keyword: 'a b', ignored: undefined })).resolves.toEqual({ ok: true });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/items?page=2&keyword=a+b', expect.objectContaining({
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
|
||||
test('serializes JSON bodies', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await post('/login', { username: 'admin' });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/login', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username: 'admin' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}));
|
||||
});
|
||||
|
||||
test('surfaces backend errors', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ detail: 'bad request' }), {
|
||||
status: 400,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
await expect(get('/bad')).rejects.toThrow('bad request');
|
||||
});
|
||||
|
||||
test('posts FormData without forcing a content type', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const form = new FormData();
|
||||
form.set('name', 'value');
|
||||
await expect(postForm('/upload', form)).resolves.toBe('ok');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/upload', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: form,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
const repoRoot = resolve(__dirname);
|
||||
|
||||
const readFrontendFile = (relativePath: string) =>
|
||||
readFileSync(resolve(repoRoot, relativePath), 'utf8');
|
||||
|
||||
const extractSingleQuotedValues = (source: string, pattern: RegExp) => {
|
||||
const values = new Set<string>();
|
||||
for (const match of source.matchAll(pattern)) {
|
||||
values.add(match[1]);
|
||||
}
|
||||
return values;
|
||||
};
|
||||
|
||||
describe('frontend navigation routing', () => {
|
||||
test('sidebar entries and App activeTab routes stay in sync', () => {
|
||||
const sidebar = readFrontendFile('components/Sidebar.tsx');
|
||||
const app = readFrontendFile('App.tsx');
|
||||
|
||||
const sidebarIDs = extractSingleQuotedValues(sidebar, /id:\s*'([^']+)'/g);
|
||||
const appRouteIDs = extractSingleQuotedValues(app, /case\s+'([^']+)'/g);
|
||||
|
||||
expect([...sidebarIDs].sort()).toEqual([...appRouteIDs].sort());
|
||||
});
|
||||
|
||||
test('item delivery shortcut opens existing automation rule modal', () => {
|
||||
const rules = readFrontendFile('components/Rules.tsx');
|
||||
const existingRuleBranch = rules.match(/if \(rule\) \{([\s\S]*?)\} else \{/);
|
||||
|
||||
expect(existingRuleBranch?.[1]).toContain('openAutomationRule(rule)');
|
||||
});
|
||||
|
||||
test('item delivery shortcut is not marked handled before async open completes', () => {
|
||||
const rules = readFrontendFile('components/Rules.tsx');
|
||||
|
||||
expect(rules).not.toContain('handledDeliveryTarget.current = initialDeliveryTarget.requestId');
|
||||
expect(rules).toContain('onDeliveryTargetHandled?.();');
|
||||
});
|
||||
|
||||
test('automation editor keeps multiple delivery contents for normal products', () => {
|
||||
const rules = readFrontendFile('components/Rules.tsx');
|
||||
|
||||
expect(rules).toContain('添加发货内容');
|
||||
expect(rules).toContain('{displayVariants.map((variant, index) => (');
|
||||
expect(rules).toContain(': variants.map(variant => ({');
|
||||
expect(rules).not.toContain(': (isMultiSpecRule ? variants : [variants[0]]).map');
|
||||
});
|
||||
|
||||
test('batch publishing help explains card fields without required-field jargon', () => {
|
||||
const itemList = readFrontendFile('components/ItemList.tsx');
|
||||
|
||||
expect(itemList).not.toContain('条件必填');
|
||||
expect(itemList).toContain('“付款后发送的卡密”怎么填');
|
||||
expect(itemList).toContain('101:1:0;102:2:3');
|
||||
expect(itemList).toContain('买家购买 3 件时会发送 6 份');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import { getItems, getOrders, getShippingRules, getValidOrders, updateShippingRule } from './api';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
const jsonResponse = (body: unknown) => new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
|
||||
test('getOrders normalizes backend order fields', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o1', order_status: 'shipped', quantity: '2' }],
|
||||
total: 1,
|
||||
})));
|
||||
const result = await getOrders(undefined, 'all', 1, 20);
|
||||
expect(result.data[0]).toMatchObject({ id: 'o1', status: 'shipped', quantity: 2 });
|
||||
expect(result.total).toBe(1);
|
||||
});
|
||||
|
||||
test('getValidOrders accepts wrapped responses', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o2', order_status: 'completed', quantity: '3' }],
|
||||
})));
|
||||
const result = await getValidOrders({ start_date: '2026-01-01', end_date: '2026-01-02' });
|
||||
expect(result).toEqual([expect.objectContaining({ id: 'o2', status: 'completed', quantity: 3 })]);
|
||||
});
|
||||
|
||||
test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
item_title: '普通商品',
|
||||
is_multi_spec: '0',
|
||||
multi_quantity_delivery: 0,
|
||||
}, {
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-2',
|
||||
item_title: '多规格商品',
|
||||
is_multi_spec: '1',
|
||||
multi_quantity_delivery: 1,
|
||||
}])));
|
||||
|
||||
const items = await getItems();
|
||||
expect(items[0]).toMatchObject({
|
||||
id: 'cookie-1-item-1',
|
||||
is_multi_spec: false,
|
||||
is_multi_qty_ship: false,
|
||||
multi_quantity_delivery: false,
|
||||
});
|
||||
expect(items[1]).toMatchObject({
|
||||
id: 'cookie-1-item-2',
|
||||
is_multi_spec: true,
|
||||
is_multi_qty_ship: true,
|
||||
multi_quantity_delivery: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('getShippingRules exposes buyer reviewed gift rules as automation rules', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
id: 12,
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
item_title: '测试商品',
|
||||
name: '评价后发送赠品 - 测试商品',
|
||||
trigger_type: 'buyer_reviewed',
|
||||
enabled: true,
|
||||
priority: 90,
|
||||
config_json: '{}',
|
||||
actions: [{
|
||||
id: 33,
|
||||
action_type: 'send_card',
|
||||
card_id: 7,
|
||||
card_name: '赠品库存',
|
||||
delivery_count: 1,
|
||||
config_json: '{"spec_name":"套餐","spec_value":"赠品"}',
|
||||
enabled: true,
|
||||
sort_order: 1,
|
||||
}],
|
||||
}])));
|
||||
|
||||
const rules = await getShippingRules();
|
||||
expect(rules[0]).toMatchObject({
|
||||
id: '12',
|
||||
trigger_type: 'buyer_reviewed',
|
||||
card_group_id: 7,
|
||||
card_group_name: '赠品库存',
|
||||
});
|
||||
expect(rules[0].variants[0]).toMatchObject({
|
||||
spec_name: '套餐',
|
||||
spec_value: '赠品',
|
||||
card_id: 7,
|
||||
});
|
||||
});
|
||||
|
||||
test('updateShippingRule posts buyer reviewed gift payload to automation-rules', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 1 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
trigger_type: 'buyer_reviewed',
|
||||
enabled: true,
|
||||
variants: [{
|
||||
spec_name: '',
|
||||
spec_value: '',
|
||||
card_id: 7,
|
||||
delivery_count: 1,
|
||||
enabled: true,
|
||||
}],
|
||||
});
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/automation-rules', expect.objectContaining({
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
}));
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body).toMatchObject({
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
name: '评价后发送赠品 - item-1',
|
||||
trigger_type: 'buyer_reviewed',
|
||||
});
|
||||
expect(body.actions).toEqual([
|
||||
expect.objectContaining({
|
||||
action_type: 'send_card',
|
||||
card_id: 7,
|
||||
sort_order: 1,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test('updateShippingRule posts every matching card action before confirm shipment', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 3 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
trigger_type: 'order_paid',
|
||||
enabled: true,
|
||||
variants: [
|
||||
{
|
||||
spec_name: '套餐',
|
||||
spec_value: '30天',
|
||||
card_id: 8,
|
||||
delivery_count: 1,
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
spec_name: '套餐',
|
||||
spec_value: '30天',
|
||||
card_id: 9,
|
||||
delivery_count: 2,
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.trigger_type).toBe('order_paid');
|
||||
expect(body.actions).toEqual([
|
||||
expect.objectContaining({
|
||||
action_type: 'send_card',
|
||||
card_id: 8,
|
||||
sort_order: 1,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
action_type: 'send_card',
|
||||
card_id: 9,
|
||||
delivery_count: 2,
|
||||
sort_order: 2,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
action_type: 'confirm_shipment',
|
||||
sort_order: 3,
|
||||
}),
|
||||
]);
|
||||
expect(JSON.parse(body.actions[0].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天' });
|
||||
expect(JSON.parse(body.actions[1].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天' });
|
||||
});
|
||||
|
||||
test('updateShippingRule posts review request text action without card requirement', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 2 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
trigger_type: 'review_missing_timeout',
|
||||
enabled: true,
|
||||
config_json: '{"after_shipped_hours":48,"max_attempts":2}',
|
||||
actions: [{
|
||||
action_type: 'send_text',
|
||||
message_template: '亲,方便的话麻烦给个评价~',
|
||||
enabled: true,
|
||||
sort_order: 1,
|
||||
}],
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.trigger_type).toBe('review_missing_timeout');
|
||||
expect(body.actions).toEqual([
|
||||
expect.objectContaining({
|
||||
action_type: 'send_text',
|
||||
card_id: 0,
|
||||
message_template: '亲,方便的话麻烦给个评价~',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
+107
-42
@@ -2,7 +2,7 @@ import { get, post, put, del, postForm } from '../request';
|
||||
import {
|
||||
LoginResponse, AccountDetail, Order, PaginatedResponse,
|
||||
AdminStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction
|
||||
} from '../types';
|
||||
|
||||
// Auth
|
||||
@@ -258,7 +258,13 @@ export const getValidOrders = async (dateRange: {start_date: string; end_date: s
|
||||
start_date: dateRange.start_date,
|
||||
end_date: dateRange.end_date
|
||||
});
|
||||
return res.orders || [];
|
||||
const orders = Array.isArray(res) ? res : (res.orders || []);
|
||||
return orders.map((order: any) => ({
|
||||
...order,
|
||||
id: order.id || order.order_id,
|
||||
status: order.status || order.order_status || 'processing',
|
||||
quantity: Number(order.quantity || 1),
|
||||
}));
|
||||
}
|
||||
|
||||
// Cards
|
||||
@@ -303,13 +309,18 @@ export const getCardDetails = async (cardId: string | number): Promise<any> => {
|
||||
};
|
||||
|
||||
// Items
|
||||
const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
value === true || value === 1 || value === '1';
|
||||
|
||||
export const getItems = async (): Promise<Item[]> => {
|
||||
const res = await get<any>('/items');
|
||||
const items = Array.isArray(res) ? res : (res.items || []);
|
||||
return items.map((item: any) => ({
|
||||
...item,
|
||||
id: item.id || `${item.cookie_id}-${item.item_id}`,
|
||||
is_multi_qty_ship: item.is_multi_qty_ship ?? item.multi_quantity_delivery ?? false,
|
||||
is_multi_spec: normalizeBooleanFlag(item.is_multi_spec),
|
||||
is_multi_qty_ship: normalizeBooleanFlag(item.is_multi_qty_ship ?? item.multi_quantity_delivery),
|
||||
multi_quantity_delivery: normalizeBooleanFlag(item.multi_quantity_delivery ?? item.is_multi_qty_ship),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -383,66 +394,120 @@ export const updateItem = async (cookieId: string, itemId: string, data: any): P
|
||||
return put(`/items/${cookieId}/${itemId}`, data);
|
||||
}
|
||||
|
||||
export const setItemMultiSpec = async (cookieId: string, itemId: string, enabled: boolean): Promise<any> => {
|
||||
return put(`/items/${cookieId}/${itemId}/multi-spec`, { is_multi_spec: enabled });
|
||||
}
|
||||
|
||||
export const setItemMultiQuantity = async (cookieId: string, itemId: string, enabled: boolean): Promise<any> => {
|
||||
return put(`/items/${cookieId}/${itemId}/multi-quantity-delivery`, { multi_quantity_delivery: enabled });
|
||||
}
|
||||
|
||||
// Rules - 发货规则 (使用正确的后端API)
|
||||
// Rules - 自动化规则
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
const res = await get<any>('/delivery-rules');
|
||||
const res = await get<any>('/automation-rules');
|
||||
const rules = Array.isArray(res) ? res : (res.data || res.rules || []);
|
||||
// 转换后端数据格式到前端格式
|
||||
return rules.map((item: any) => ({
|
||||
id: String(item.id),
|
||||
name: item.description || item.keyword || '',
|
||||
item_keyword: item.keyword || '',
|
||||
name: item.name || '',
|
||||
trigger_type: item.trigger_type || 'order_paid',
|
||||
item_keyword: item.item_title || item.item_id || '',
|
||||
cookie_id: item.cookie_id || '',
|
||||
item_id: item.item_id || '',
|
||||
item_title: item.item_title || '',
|
||||
card_group_id: item.card_id || 0,
|
||||
card_group_name: item.card_name || '',
|
||||
priority: item.delivery_count || 1,
|
||||
card_group_id: Number((item.actions || []).find((a: any) => a.action_type === 'send_card')?.card_id || 0),
|
||||
card_group_name: (item.actions || []).find((a: any) => a.action_type === 'send_card')?.card_name || '',
|
||||
priority: item.priority || 100,
|
||||
enabled: item.enabled || false,
|
||||
variants: (item.variants || []).map((variant: any) => ({
|
||||
id: variant.id ? String(variant.id) : undefined,
|
||||
spec_name: variant.spec_name || '',
|
||||
spec_value: variant.spec_value || '',
|
||||
card_id: Number(variant.card_id || 0),
|
||||
card_name: variant.card_name || '',
|
||||
card_type: variant.card_type,
|
||||
delivery_count: Number(variant.delivery_count || 1),
|
||||
enabled: variant.enabled !== false,
|
||||
config_json: item.config_json || '{}',
|
||||
actions: (item.actions || []).map((action: any) => ({
|
||||
id: action.id ? String(action.id) : undefined,
|
||||
action_type: action.action_type,
|
||||
card_id: Number(action.card_id || 0),
|
||||
card_name: action.card_name || '',
|
||||
delivery_count: Number(action.delivery_count || 1),
|
||||
message_template: action.message_template || '',
|
||||
delay_seconds: Number(action.delay_seconds || 0),
|
||||
config_json: action.config_json || '{}',
|
||||
enabled: action.enabled !== false,
|
||||
sort_order: Number(action.sort_order || 0),
|
||||
})),
|
||||
variants: (item.actions || [])
|
||||
.filter((action: any) => action.action_type === 'send_card')
|
||||
.map((action: any) => {
|
||||
let cfg: any = {};
|
||||
try { cfg = JSON.parse(action.config_json || '{}'); } catch {}
|
||||
return {
|
||||
id: action.id ? String(action.id) : undefined,
|
||||
spec_name: cfg.spec_name || '',
|
||||
spec_value: cfg.spec_value || '',
|
||||
card_id: Number(action.card_id || 0),
|
||||
card_name: action.card_name || '',
|
||||
delivery_count: Number(action.delivery_count || 1),
|
||||
enabled: action.enabled !== false,
|
||||
config_json: action.config_json || '{}',
|
||||
};
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
const orderAutomationActions = (triggerType: string, actions: AutomationAction[]) => {
|
||||
if (triggerType !== 'order_paid') {
|
||||
return actions.map((action, index) => ({ ...action, sort_order: action.sort_order || index + 1 }));
|
||||
}
|
||||
const sendCards = actions
|
||||
.filter(action => action.action_type === 'send_card')
|
||||
.map((action, index) => ({ ...action, sort_order: index + 1 }));
|
||||
const others = actions.filter(action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment');
|
||||
return [
|
||||
...sendCards,
|
||||
...others.map((action, index) => ({ ...action, sort_order: sendCards.length + index + 1 })),
|
||||
{ action_type: 'confirm_shipment' as const, enabled: true, sort_order: sendCards.length + others.length + 1 },
|
||||
];
|
||||
};
|
||||
|
||||
export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<any> => {
|
||||
const triggerType = rule.trigger_type || 'order_paid';
|
||||
const triggerName: Record<string, string> = {
|
||||
order_paid: '付款后自动发货',
|
||||
buyer_reviewed: '评价后发送赠品',
|
||||
review_missing_timeout: '超时未评价求评价',
|
||||
};
|
||||
const generatedName = [
|
||||
triggerName[triggerType] || '自动化规则',
|
||||
rule.item_title || rule.item_id || rule.cookie_id || '',
|
||||
].filter(Boolean).join(' - ');
|
||||
const baseActions: AutomationAction[] = rule.variants && rule.variants.length > 0
|
||||
? rule.variants.map((variant, index) => ({
|
||||
action_type: 'send_card' as const,
|
||||
card_id: variant.card_id,
|
||||
delivery_count: variant.delivery_count || 1,
|
||||
enabled: variant.enabled !== false,
|
||||
sort_order: index + 1,
|
||||
config_json: JSON.stringify({ spec_name: variant.spec_name || '', spec_value: variant.spec_value || '' }),
|
||||
}))
|
||||
: (rule.actions && rule.actions.length > 0 ? rule.actions : [{
|
||||
action_type: 'send_card' as const,
|
||||
card_id: rule.card_group_id || 0,
|
||||
delivery_count: 1,
|
||||
enabled: true,
|
||||
sort_order: 1,
|
||||
}]);
|
||||
const actions = orderAutomationActions(triggerType, baseActions);
|
||||
const payload = {
|
||||
keyword: rule.item_keyword,
|
||||
cookie_id: rule.cookie_id || '',
|
||||
item_id: rule.item_id || '',
|
||||
card_id: rule.card_group_id,
|
||||
delivery_count: rule.priority,
|
||||
name: (rule.name || '').trim() || generatedName || '自动化规则',
|
||||
trigger_type: triggerType,
|
||||
enabled: rule.enabled ?? true,
|
||||
description: rule.name,
|
||||
// 规格映射更新时后端会删除旧记录并重建;不要回传只用于展示的
|
||||
// id/card_name/card_type,避免把字符串 id 解码到 Go int64 时失败。
|
||||
variants: (rule.variants || []).map((variant) => ({
|
||||
spec_name: variant.spec_name,
|
||||
spec_value: variant.spec_value,
|
||||
card_id: variant.card_id,
|
||||
delivery_count: variant.delivery_count,
|
||||
enabled: variant.enabled,
|
||||
priority: rule.priority || 100,
|
||||
config_json: rule.config_json || '{}',
|
||||
actions: actions.map((action, index) => ({
|
||||
action_type: action.action_type,
|
||||
card_id: action.card_id || 0,
|
||||
delivery_count: action.delivery_count || 1,
|
||||
message_template: action.message_template || '',
|
||||
delay_seconds: action.delay_seconds || 0,
|
||||
config_json: action.config_json || '{}',
|
||||
enabled: action.enabled !== false,
|
||||
sort_order: action.sort_order || index + 1,
|
||||
})),
|
||||
};
|
||||
return rule.id ? put(`/delivery-rules/${rule.id}`, payload) : post('/delivery-rules', payload);
|
||||
return rule.id ? put(`/automation-rules/${rule.id}`, payload) : post('/automation-rules', payload);
|
||||
}
|
||||
|
||||
export const deleteShippingRule = async (id: string): Promise<any> => del(`/delivery-rules/${id}`);
|
||||
export const deleteShippingRule = async (id: string): Promise<any> => del(`/automation-rules/${id}`);
|
||||
|
||||
// Rules - 关键词回复规则 (使用关键词API)
|
||||
export const getReplyRules = async (cookieId?: string): Promise<ReplyRule[]> => {
|
||||
|
||||
+23
-2
@@ -76,6 +76,7 @@ export interface Order {
|
||||
quantity: number;
|
||||
amount: string;
|
||||
status: OrderStatus;
|
||||
order_status?: OrderStatus;
|
||||
receiver_name?: string;
|
||||
receiver_phone?: string;
|
||||
receiver_address?: string;
|
||||
@@ -131,21 +132,40 @@ export interface Item {
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout';
|
||||
export type AutomationActionType = 'confirm_shipment' | 'send_card' | 'send_text';
|
||||
|
||||
// Rules
|
||||
export interface ShippingRule {
|
||||
id: string;
|
||||
name: string;
|
||||
item_keyword: string; // Matches item title
|
||||
trigger_type: AutomationTriggerType;
|
||||
item_keyword: string; // Legacy UI helper
|
||||
cookie_id?: string;
|
||||
item_id?: string;
|
||||
item_title?: string;
|
||||
card_group_id: number; // ID from Card list
|
||||
card_group_id: number; // First send_card action card id
|
||||
card_group_name?: string; // UI helper
|
||||
priority: number;
|
||||
enabled: boolean;
|
||||
config_json?: string;
|
||||
actions: AutomationAction[];
|
||||
variants: ShippingVariant[];
|
||||
}
|
||||
|
||||
export interface AutomationAction {
|
||||
id?: string;
|
||||
action_type: AutomationActionType;
|
||||
card_id?: number;
|
||||
card_name?: string;
|
||||
delivery_count?: number;
|
||||
message_template?: string;
|
||||
delay_seconds?: number;
|
||||
config_json?: string;
|
||||
enabled: boolean;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
export interface ShippingVariant {
|
||||
id?: string;
|
||||
spec_name: string;
|
||||
@@ -155,6 +175,7 @@ export interface ShippingVariant {
|
||||
card_type?: Card['type'];
|
||||
delivery_count: number;
|
||||
enabled: boolean;
|
||||
config_json?: string;
|
||||
}
|
||||
|
||||
export interface ReplyRule {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module xianyu-go
|
||||
|
||||
go 1.26.1
|
||||
go 1.26.4
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.15
|
||||
|
||||
+3
-11
@@ -15,7 +15,7 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// CookieName 会话 Cookie 名(与 Python 端 SESSION_COOKIE_NAME 一致)。
|
||||
// CookieName 是会话 Cookie 名。
|
||||
const CookieName = "session"
|
||||
|
||||
// CookieMaxAge 会话有效期(24 小时)。
|
||||
@@ -58,16 +58,6 @@ func (s *Service) Login(ctx context.Context, username, password string) (string,
|
||||
return sid, user, nil
|
||||
}
|
||||
|
||||
// CreateSessionForUser 为已加载的 user 创建会话,返回 session ID。
|
||||
func (s *Service) CreateSessionForUser(user *db.User) string {
|
||||
sid, err := s.Store.Sessions.Create(context.Background(), user)
|
||||
if err != nil {
|
||||
s.Logger.Error("创建会话失败", "err", err)
|
||||
return ""
|
||||
}
|
||||
return sid
|
||||
}
|
||||
|
||||
// Logout 删除会话并返回清 Cookie 所需操作。
|
||||
func (s *Service) Logout(ctx context.Context, sessionID string) {
|
||||
if sessionID != "" {
|
||||
@@ -77,6 +67,7 @@ func (s *Service) Logout(ctx context.Context, sessionID string) {
|
||||
|
||||
// SetSessionCookie 把会话 ID 写入响应 Cookie(HttpOnly + SameSite=Lax)。
|
||||
func (s *Service) SetSessionCookie(w http.ResponseWriter, sessionID string) {
|
||||
// #nosec G124 -- HttpOnly/SameSite 始终设置;Secure 由部署是否启用 HTTPS 决定。
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: CookieName,
|
||||
Value: sessionID,
|
||||
@@ -90,6 +81,7 @@ func (s *Service) SetSessionCookie(w http.ResponseWriter, sessionID string) {
|
||||
|
||||
// ClearSessionCookie 清除会话 Cookie。
|
||||
func (s *Service) ClearSessionCookie(w http.ResponseWriter) {
|
||||
// #nosec G124 -- 清除 Cookie 必须与创建时使用相同的 Secure 配置。
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: CookieName,
|
||||
Value: "",
|
||||
|
||||
@@ -66,17 +66,12 @@ func cookiesToMap(cs []playwright.Cookie) map[string]string {
|
||||
return m
|
||||
}
|
||||
|
||||
// cookiesToStr 把 playwright Cookie 切片拼成字符串。
|
||||
func cookiesToStr(cs []playwright.Cookie) string {
|
||||
m := cookiesToMap(cs)
|
||||
return cookieMarshal(m)
|
||||
}
|
||||
|
||||
// rng 用于浏览器流程的随机化(轨迹、stealth 参数)。全局,进程级足够。
|
||||
// rng 只用于模拟浏览器轨迹和指纹扰动,不用于凭证或安全令牌。
|
||||
// #nosec G404 -- 此处需要可重复的非密码学伪随机序列。
|
||||
var rng = rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
// stealthScript 生成隐身 JS(移植自 xianyu_slider_stealth._get_stealth_script)。
|
||||
// 原 Python 用 f-string 插入随机值;这里用占位符 + Go 运行时替换。
|
||||
// 使用占位符并在 Go 运行时替换随机值。
|
||||
func stealthScript() string {
|
||||
pluginCount := rng.Intn(6) + 3 // 3-8
|
||||
hwCores := []int{2, 4, 6, 8}[rng.Intn(4)]
|
||||
|
||||
@@ -80,10 +80,3 @@ func TestStealthScriptUnique(t *testing.T) {
|
||||
t.Fatal("stealth 脚本多次生成应出现随机差异")
|
||||
}
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -1,12 +1,5 @@
|
||||
// Package browser 用 playwright-go 在进程内驱动 Chromium,替换原 Python sidecar。
|
||||
// 首次使用时自动下载 Chromium(playwright.Install),无需手动启动任何外部服务。
|
||||
//
|
||||
// 移植自原项目:
|
||||
// - utils/browser_pool.py → Manager 上下文池
|
||||
// - utils/xianyu_slider_stealth.py → stealth.go + slider.go
|
||||
// - utils/item_search.py → search.go
|
||||
// - utils/order_fetcher_optimized.py → orders.go
|
||||
// - XianyuAutoAsync.refresh_cookies_from_qr_login → qrrefresh.go
|
||||
// Package browser 用 playwright-go 在进程内驱动 Chromium。
|
||||
// 首次使用时自动下载 Chromium(playwright.Install),无需手动启动外部服务。
|
||||
package browser
|
||||
|
||||
import (
|
||||
@@ -22,7 +15,7 @@ import (
|
||||
"xianyu-go/internal/xianyu"
|
||||
)
|
||||
|
||||
// 默认 UA / 视口,与 Python 端一致。
|
||||
// 默认 UA、语言、时区与视口。
|
||||
const (
|
||||
defaultUA = xianyu.BrowserUA
|
||||
defaultW = 1920
|
||||
@@ -33,7 +26,7 @@ const (
|
||||
goofishIMURL = "https://www.goofish.com/im"
|
||||
)
|
||||
|
||||
// chromiumLaunchArgs 统一 Chromium 启动参数(取自 browser_pool._create_browser)。
|
||||
// chromiumLaunchArgs 统一 Chromium 启动参数。
|
||||
func chromiumLaunchArgs() []string {
|
||||
return []string{
|
||||
"--no-sandbox",
|
||||
@@ -78,12 +71,10 @@ type Manager struct {
|
||||
}
|
||||
|
||||
type poolEntry struct {
|
||||
cookieID string
|
||||
browser playwright.Browser
|
||||
context playwright.BrowserContext
|
||||
lastUsed time.Time
|
||||
userData string // 持久化目录(密码登录用),空表示非持久化
|
||||
persistent bool
|
||||
cookieID string
|
||||
browser playwright.Browser
|
||||
context playwright.BrowserContext
|
||||
lastUsed time.Time
|
||||
}
|
||||
|
||||
// NewManager 构造。logger 为 nil 用默认。
|
||||
@@ -146,14 +137,6 @@ func (m *Manager) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ping 暴露给 health 检查:playwright 是否就绪。
|
||||
func (m *Manager) ping(ctx context.Context) error {
|
||||
if err := m.init(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newPage 从池中取(或创建)一个 context,返回新 page + 释放函数。
|
||||
// 每次请求新建 page,避免并发导航冲突(与 browser_pool.get_browser 一致)。
|
||||
func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headless bool) (playwright.Page, func(), error) {
|
||||
@@ -208,8 +191,8 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
|
||||
}
|
||||
context, err := browser.NewContext(playwright.BrowserNewContextOptions{
|
||||
UserAgent: playwright.String(defaultUA),
|
||||
Viewport: &playwright.Size{Width: defaultW, Height: defaultH},
|
||||
Locale: playwright.String(defaultLang),
|
||||
Viewport: &playwright.Size{Width: defaultW, Height: defaultH},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -161,10 +161,8 @@ func parseAPIResponse(od *OrderDetail, data map[string]any) {
|
||||
}
|
||||
}
|
||||
|
||||
var amountRE = regexp.MustCompile(`[\d.]+`)
|
||||
var currencyAmountRE = regexp.MustCompile(`[¥¥]\s*([0-9]+(?:\.[0-9]{1,2})?)`)
|
||||
var plainAmountRE = regexp.MustCompile(`^\s*([0-9]+(?:\.[0-9]{1,2})?)\s*$`)
|
||||
var orderTimeRE = regexp.MustCompile(`\d{4}[-/]\d{2}[-/]\d{2}\s+\d{2}:\d{2}(?::\d{2})?`)
|
||||
|
||||
func parseDOMContent(page playwright.Page, od *OrderDetail) {
|
||||
// 金额。
|
||||
|
||||
@@ -20,20 +20,6 @@ func TestOrderStatusMap(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseWantCount(t *testing.T) {
|
||||
cases := map[string]int{
|
||||
"3": 3,
|
||||
"1.5万": 15000,
|
||||
"2万": 20000,
|
||||
"100": 100,
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := parseWantCount(in); got != want {
|
||||
t.Errorf("parseWantCount(%q) = %d, want %d", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAPIResponseStatusCode(t *testing.T) {
|
||||
od := &OrderDetail{}
|
||||
data := map[string]any{
|
||||
|
||||
@@ -152,47 +152,5 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
return cookieStr, unb, nil
|
||||
}
|
||||
|
||||
// gotoWithFallback 访问 URL,超时降级(domcontentloaded→load→无等待)。
|
||||
func gotoWithFallback(page playwright.Page, url string) error {
|
||||
to := func(ms float64) *float64 { return &ms }
|
||||
if _, err := page.Goto(url, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: to(15000),
|
||||
}); err == nil {
|
||||
return nil
|
||||
}
|
||||
if _, err := page.Goto(url, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateLoad,
|
||||
Timeout: to(20000),
|
||||
}); err == nil {
|
||||
return nil
|
||||
}
|
||||
_, err := page.Goto(url, playwright.PageGotoOptions{Timeout: to(25000)})
|
||||
return err
|
||||
}
|
||||
|
||||
func reloadWithFallback(page playwright.Page) error {
|
||||
to := func(ms float64) *float64 { return &ms }
|
||||
if _, err := page.Reload(playwright.PageReloadOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: to(12000),
|
||||
}); err == nil {
|
||||
return nil
|
||||
}
|
||||
_, err := page.Reload(playwright.PageReloadOptions{
|
||||
WaitUntil: playwright.WaitUntilStateLoad,
|
||||
Timeout: to(15000),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// sleep 可被测试替换。
|
||||
var sleep = time.Sleep
|
||||
|
||||
func cookieNames(m map[string]string) []string {
|
||||
names := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
names = append(names, k)
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
)
|
||||
|
||||
const mtopSearchURL = "h5api.m.goofish.com/h5/mtop.taobao.idlemtopsearch.pc.search"
|
||||
|
||||
// SearchItem 商品搜索结果。
|
||||
type SearchItem struct {
|
||||
Title string `json:"title"`
|
||||
Price string `json:"price"`
|
||||
WantCount int `json:"want_count"`
|
||||
Area string `json:"area"`
|
||||
UserNick string `json:"user_nick"`
|
||||
ItemURL string `json:"item_url"`
|
||||
PicURL string `json:"pic_url"`
|
||||
ItemID string `json:"item_id"`
|
||||
}
|
||||
|
||||
// SearchItems 搜索闲鱼商品,返回解析结果。
|
||||
// 移植自 utils/item_search.py search_items。
|
||||
func (m *Manager) SearchItems(ctx context.Context, keyword, cookieID, cookieValue string, page, pageSize int) (map[string]any, error) {
|
||||
if err := m.init(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pw, release, err := m.newPage(ctx, cookieID, cookieValue, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
var mu sync.Mutex
|
||||
var responses []map[string]any
|
||||
|
||||
pw.OnResponse(func(resp playwright.Response) {
|
||||
if !strings.Contains(resp.URL(), mtopSearchURL) {
|
||||
return
|
||||
}
|
||||
if resp.Status() != 200 {
|
||||
return
|
||||
}
|
||||
var body map[string]any
|
||||
if err := resp.JSON(&body); err == nil {
|
||||
mu.Lock()
|
||||
responses = append(responses, body)
|
||||
mu.Unlock()
|
||||
}
|
||||
})
|
||||
|
||||
// 访问首页、注入 cookie、刷新。
|
||||
if _, err := pw.Goto("https://www.goofish.com", playwright.PageGotoOptions{Timeout: playwright.Float(30000)}); err != nil {
|
||||
return nil, fmt.Errorf("访问 goofish.com 失败: %w", err)
|
||||
}
|
||||
if cookieValue != "" {
|
||||
_ = addCookieStr(pw.Context(), cookieValue)
|
||||
_, _ = pw.Reload()
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
|
||||
// 填搜索框并提交。
|
||||
_, _ = pw.WaitForSelector(`input[class*="search-input"]`, playwright.PageWaitForSelectorOptions{Timeout: playwright.Float(10000)})
|
||||
_ = pw.Fill(`input[class*="search-input"]`, keyword)
|
||||
_ = pw.Click(`button[type="submit"]`)
|
||||
|
||||
// 等待 mtop 响应。
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
mu.Lock()
|
||||
got := len(responses)
|
||||
mu.Unlock()
|
||||
if got > 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
|
||||
// 可能出现滑块。
|
||||
content, _ := pw.Content()
|
||||
if strings.Contains(content, "nc-container") || strings.Contains(content, "scratch-captcha") {
|
||||
if err := solveSlider(pw, isScratchCaptcha(content), m.logger); err != nil {
|
||||
m.logger.Warn("搜索滑块处理失败", "err", err)
|
||||
}
|
||||
// 重试搜索。
|
||||
_ = pw.Fill(`input[class*="search-input"]`, keyword)
|
||||
_ = pw.Click(`button[type="submit"]`)
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(responses) == 0 {
|
||||
return map[string]any{"items": []any{}, "total": 0, "is_real_data": false}, nil
|
||||
}
|
||||
|
||||
items := parseSearchResponse(responses[0])
|
||||
return map[string]any{"items": items, "total": len(items), "is_real_data": true, "source": "browser"}, nil
|
||||
}
|
||||
|
||||
// parseSearchResponse 解析 mtop 搜索响应(移植自 _parse_real_item)。
|
||||
func parseSearchResponse(body map[string]any) []SearchItem {
|
||||
data, _ := body["data"].(map[string]any)
|
||||
list, _ := data["resultList"].([]any)
|
||||
var items []SearchItem
|
||||
for _, raw := range list {
|
||||
item := parseSearchItem(raw)
|
||||
if item != nil {
|
||||
items = append(items, *item)
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
var wantRE = regexp.MustCompile(`(\d+(?:\.\d+)?(?:万)?)\s*人想要`)
|
||||
|
||||
func parseSearchItem(raw any) *SearchItem {
|
||||
r, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
d, _ := r["data"].(map[string]any)
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
itemM, _ := d["item"].(map[string]any)
|
||||
if itemM == nil {
|
||||
return nil
|
||||
}
|
||||
main, _ := itemM["main"].(map[string]any)
|
||||
if main == nil {
|
||||
return nil
|
||||
}
|
||||
exContent, _ := main["exContent"].(map[string]any)
|
||||
clickParam, _ := main["clickParam"].(map[string]any)
|
||||
args, _ := clickParam["args"].(map[string]any)
|
||||
|
||||
title, _ := exContent["title"].(string)
|
||||
area, _ := exContent["area"].(string)
|
||||
userNick, _ := exContent["userNickName"].(string)
|
||||
picURL, _ := exContent["picUrl"].(string)
|
||||
targetURL, _ := exContent["targetUrl"].(string)
|
||||
itemID, _ := args["content"].(string)
|
||||
|
||||
// 价格:取 priceList 中的文字拼接。
|
||||
price := ""
|
||||
if pl, ok := exContent["priceList"].([]any); ok {
|
||||
var parts []string
|
||||
for _, p := range pl {
|
||||
if pm, ok := p.(map[string]any); ok {
|
||||
if t, ok := pm["text"].(string); ok {
|
||||
parts = append(parts, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
price = strings.Join(parts, "")
|
||||
price = strings.TrimPrefix(price, "当前价")
|
||||
}
|
||||
|
||||
// 想要数。
|
||||
wantCount := 0
|
||||
if tags, ok := exContent["fishTags"].([]any); ok {
|
||||
for _, t := range tags {
|
||||
if s, ok := t.(string); ok {
|
||||
if m := wantRE.FindStringSubmatch(s); len(m) > 1 {
|
||||
wantCount = parseWantCount(m[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
itemURL := strings.ReplaceAll(targetURL, "fleamarket://", "https://www.goofish.com/")
|
||||
|
||||
return &SearchItem{
|
||||
Title: title,
|
||||
Price: price,
|
||||
WantCount: wantCount,
|
||||
Area: area,
|
||||
UserNick: userNick,
|
||||
PicURL: picURL,
|
||||
ItemURL: itemURL,
|
||||
ItemID: itemID,
|
||||
}
|
||||
}
|
||||
|
||||
func parseWantCount(s string) int {
|
||||
if strings.HasSuffix(s, "万") {
|
||||
f, err := strconv.ParseFloat(strings.TrimSuffix(s, "万"), 64)
|
||||
if err == nil {
|
||||
return int(f * 10000)
|
||||
}
|
||||
}
|
||||
n, _ := strconv.Atoi(s)
|
||||
return n
|
||||
}
|
||||
|
||||
// marshalSearchItems 供 HTTP handler 序列化。
|
||||
func marshalSearchItems(items []SearchItem) []map[string]any {
|
||||
result := make([]map[string]any, 0, len(items))
|
||||
for _, it := range items {
|
||||
b, _ := json.Marshal(it)
|
||||
var m map[string]any
|
||||
_ = json.Unmarshal(b, &m)
|
||||
result = append(result, m)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
@@ -18,10 +17,6 @@ var sliderButtonSelectors = []string{
|
||||
var sliderTrackSelectors = []string{
|
||||
"#nc_1_n1t", ".nc_scale", ".nc_1_n1t",
|
||||
}
|
||||
var sliderContainerSelectors = []string{
|
||||
"#nc_1_n1z", "#baxia-dialog-content", ".nc-container", ".nc_wrapper",
|
||||
"#nocaptcha", ".scratch-captcha-container",
|
||||
}
|
||||
var sliderRetrySelectors = []string{
|
||||
".nc-lang-cnt", "#nc_1_n1z",
|
||||
}
|
||||
@@ -45,7 +40,7 @@ func generateTrajectory(distance float64) []trajectoryPoint {
|
||||
progress := float64(i+1) / float64(steps)
|
||||
x := overshoot * math.Pow(progress, 1.5)
|
||||
y := float64(rng.Intn(3)) // 0-2 px
|
||||
d := time.Duration((baseDelay*(0.9+0.2*float64(rng.Intn(11))/10.0))*float64(time.Millisecond))
|
||||
d := time.Duration((baseDelay * (0.9 + 0.2*float64(rng.Intn(11))/10.0)) * float64(time.Millisecond))
|
||||
pts[i] = trajectoryPoint{x: x, y: y, delay: d}
|
||||
}
|
||||
return pts
|
||||
@@ -58,42 +53,6 @@ func isScratchCaptcha(content string) bool {
|
||||
strings.Contains(content, "scratch-captcha-slider")
|
||||
}
|
||||
|
||||
// SliderVerify 访问风控验证 URL,自动过滑块,返回更新后的 cookie map(含 x5sec)。
|
||||
// 移植自 xianyu_slider_stealth.py run() + solve_slider()。
|
||||
func (m *Manager) SliderVerify(ctx context.Context, url, cookieID string, headless bool) (map[string]string, error) {
|
||||
if err := m.init(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, release, err := m.newPage(ctx, cookieID, "", headless)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
if _, err := page.Goto(url, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(30000),
|
||||
}); err != nil {
|
||||
return nil, fmt.Errorf("访问验证 URL 失败: %w", err)
|
||||
}
|
||||
time.Sleep(300 + time.Duration(rng.Intn(500))*time.Millisecond)
|
||||
|
||||
content, _ := page.Content()
|
||||
if !strings.Contains(content, "验证") && !strings.Contains(content, "captcha") && !strings.Contains(content, "slider") {
|
||||
// 页面不含验证码,直接提取 cookie。
|
||||
m.logger.Info("页面无验证码,直接提取 cookie")
|
||||
return extractPageCookies(page)
|
||||
}
|
||||
|
||||
scratch := isScratchCaptcha(content)
|
||||
if err := solveSlider(page, scratch, m.logger); err != nil {
|
||||
return nil, fmt.Errorf("滑块验证失败: %w", err)
|
||||
}
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
return extractPageCookies(page)
|
||||
}
|
||||
|
||||
// solveSlider 在 page 上求解滑块,最多重试 3 次。
|
||||
func solveSlider(page playwright.Page, scratch bool, logger interface {
|
||||
Info(string, ...any)
|
||||
@@ -176,7 +135,7 @@ func calculateSlideDistance(btn, track playwright.ElementHandle, scratch bool) (
|
||||
return dist, nil
|
||||
}
|
||||
|
||||
// simulateSlide 模拟人类滑动(移植自 simulate_slide)。
|
||||
// simulateSlide 模拟人类滑动。
|
||||
func simulateSlide(page playwright.Page, btn playwright.ElementHandle, distance float64) error {
|
||||
bb, err := btn.BoundingBox()
|
||||
if err != nil || bb == nil {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package browser
|
||||
|
||||
// stealthTemplate 是从 utils/xianyu_slider_stealth.py _get_stealth_script 原样移植的
|
||||
// 浏览器侧反检测 JS。Python 用 f-string 插入随机值,这里用 {{占位符}},由
|
||||
// stealthTemplate 是浏览器侧反检测 JS。模板使用 {{占位符}},由
|
||||
// stealthScript() 在 Go 侧生成随机值后替换。JS 本身未改动。
|
||||
const stealthTemplate = `
|
||||
// 隐藏webdriver属性
|
||||
|
||||
@@ -13,7 +13,7 @@ type Cookies struct {
|
||||
}
|
||||
|
||||
// Save 保存/更新 cookie。user_id 为 0 时:复用现有记录的 user_id,若无则报错
|
||||
// (对应 Python 端"系统未初始化不应兜底为 1"的安全修正)。
|
||||
// 系统未初始化时不兜底到默认用户。
|
||||
func (c *Cookies) Save(ctx context.Context, cookieID, cookieValue string, userID int64) error {
|
||||
if userID == 0 {
|
||||
var existing int64
|
||||
@@ -111,7 +111,7 @@ func (c *Cookies) GetDetails(ctx context.Context, cookieID string) (*CookieDetai
|
||||
d.ShowBrowser = showBrowser != 0
|
||||
d.PauseDuration = 10
|
||||
if pauseDuration.Valid {
|
||||
// 0 是有效值(表示不暂停),与 Python 端一致。
|
||||
// 0 是有效值,表示不暂停。
|
||||
d.PauseDuration = int(pauseDuration.Int64)
|
||||
}
|
||||
return &d, nil
|
||||
|
||||
@@ -3,7 +3,6 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ---- 关键字 CRUD ----
|
||||
@@ -257,7 +256,7 @@ func (s *SystemSettings) Set(ctx context.Context, key, value string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// PublicKeys 公开设置键白名单(前端登录页等无需登录可读)。
|
||||
// PublicSystemKeys 是公开设置键白名单(前端登录页等无需登录可读)。
|
||||
var PublicSystemKeys = map[string]bool{
|
||||
"theme_color": true, "registration_enabled": true,
|
||||
"show_default_login_info": true, "login_captcha_enabled": true,
|
||||
@@ -371,6 +370,3 @@ func (i *Items) SetMultiQuantity(ctx context.Context, cookieID, itemID string, o
|
||||
boolToInt(on), cookieID, itemID)
|
||||
return err
|
||||
}
|
||||
|
||||
// 防止 fmt 未用。
|
||||
var _ = fmt.Sprintf
|
||||
@@ -0,0 +1,106 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtraRepositoriesCRUD(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if ok, err := store.Users.Create(ctx, "user1", "[email protected]", "pw"); err != nil || !ok {
|
||||
t.Fatalf("create user: %v, %v", ok, err)
|
||||
}
|
||||
user, _ := store.Users.GetByUsername(ctx, "user1")
|
||||
if err := store.Cookies.Save(ctx, "acc1", "unb=1", user.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id, err := store.Keywords.Add(ctx, "acc1", "hello", "world", "item1", "text", "")
|
||||
if err != nil || id == 0 {
|
||||
t.Fatalf("add keyword: %d, %v", id, err)
|
||||
}
|
||||
keywords, _ := store.Keywords.AllRows(ctx, "acc1")
|
||||
if len(keywords) != 1 || keywords[0].Reply != "world" {
|
||||
t.Fatalf("keywords = %#v", keywords)
|
||||
}
|
||||
if err := store.Keywords.DeleteByIndex(ctx, "acc1", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Keywords.DeleteByIndex(ctx, "acc1", 0); err != ErrNotFound {
|
||||
t.Fatalf("delete missing keyword = %v", err)
|
||||
}
|
||||
|
||||
if err := store.ItemReps.Set(ctx, "acc1", "item1", "reply"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replies, _ := store.ItemReps.AllForUser(ctx, "acc1")
|
||||
if len(replies) != 1 || replies[0].ReplyContent != "reply" {
|
||||
t.Fatalf("item replies = %#v", replies)
|
||||
}
|
||||
if err := store.ItemReps.Delete(ctx, "acc1", "item1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
item := &ItemInfoRow{CookieID: "acc1", ItemID: "item1", ItemTitle: "title", ItemPrice: "9.90"}
|
||||
if err := store.Items.Upsert(ctx, item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Items.SetMultiSpec(ctx, "acc1", "item1", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Items.SetMultiQuantity(ctx, "acc1", "item1", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.Items.AllForCookie(ctx, "acc1")
|
||||
if len(items) != 1 || !items[0].IsMultiSpec || !items[0].MultiQuantityDelivery {
|
||||
t.Fatalf("items = %#v", items)
|
||||
}
|
||||
if err := store.Items.UpsertBasic(ctx, &ItemInfoRow{CookieID: "acc1", ItemID: "item1", ItemTitle: "updated"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ = store.Items.AllForCookie(ctx, "acc1")
|
||||
if items[0].ItemTitle != "updated" || !items[0].IsMultiSpec {
|
||||
t.Fatalf("upsert basic overwrote flags: %#v", items[0])
|
||||
}
|
||||
|
||||
channelID, err := store.Notifications.CreateChannel(ctx, &NotificationChannelRow{
|
||||
Name: "webhook", Type: "webhook", Config: `{}`, Enabled: true, UserID: user.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Notifications.SetBindings(ctx, "acc1", []int64{channelID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bindings, _ := store.Notifications.AccountBindings(ctx, "acc1")
|
||||
if len(bindings) != 1 || bindings[0] != channelID {
|
||||
t.Fatalf("bindings = %#v", bindings)
|
||||
}
|
||||
channels, _ := store.Notifications.AllChannelsForUser(ctx, user.ID)
|
||||
if len(channels) != 1 || !channels[0].Enabled {
|
||||
t.Fatalf("channels = %#v", channels)
|
||||
}
|
||||
channels[0].Name = "updated"
|
||||
if err := store.Notifications.UpdateChannel(ctx, &channels[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Notifications.DeleteChannel(ctx, channelID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Settings.Set(ctx, "private_key", "secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
public, err := store.Settings.Public(ctx)
|
||||
if err != nil || public["theme_color"] != "blue" || public["private_key"] != "" {
|
||||
t.Fatalf("public settings = %#v, %v", public, err)
|
||||
}
|
||||
if err := store.Items.Delete(ctx, "acc1", "item1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -35,9 +35,7 @@ type ItemPublishBatchRow struct {
|
||||
PostageMode string
|
||||
Postage string
|
||||
ImagesJSON string
|
||||
AutoCreateDeliveryRule bool
|
||||
CardGroupID int64
|
||||
DeliveryCount int
|
||||
AutomationJSON string
|
||||
Status string
|
||||
ItemID string
|
||||
ItemURL string
|
||||
@@ -68,9 +66,6 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
if row.PostageMode == "" {
|
||||
row.PostageMode = "free"
|
||||
}
|
||||
if row.DeliveryCount <= 0 {
|
||||
row.DeliveryCount = 1
|
||||
}
|
||||
if row.Status == "" {
|
||||
row.Status = "pending"
|
||||
}
|
||||
@@ -80,14 +75,17 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
if row.RawJSON == "" {
|
||||
row.RawJSON = "{}"
|
||||
}
|
||||
if row.AutomationJSON == "" {
|
||||
row.AutomationJSON = "{}"
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO item_publish_batch_rows
|
||||
(batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,auto_create_delivery_rule,card_group_id,delivery_count,status,error_message,raw_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
images_json,automation_json,status,error_message,raw_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
batch.ID, row.RowNo, row.CookieID, row.Title, row.Description, row.Price, row.OriginalPrice,
|
||||
row.Quantity, row.PostageMode, row.Postage, row.ImagesJSON, boolToInt(row.AutoCreateDeliveryRule),
|
||||
row.CardGroupID, row.DeliveryCount, row.Status, row.ErrorMessage, row.RawJSON); err != nil {
|
||||
row.Quantity, row.PostageMode, row.Postage, row.ImagesJSON, row.AutomationJSON,
|
||||
row.Status, row.ErrorMessage, row.RawJSON); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -114,7 +112,7 @@ func (b *ItemPublishBatches) Get(ctx context.Context, userID int64, id string) (
|
||||
func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPublishBatchRow, error) {
|
||||
rows, err := b.DB.QueryContext(ctx,
|
||||
`SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,auto_create_delivery_rule,card_group_id,delivery_count,status,item_id,item_url,error_message,
|
||||
images_json,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
raw_json,COALESCE(created_at,''),COALESCE(updated_at,'')
|
||||
FROM item_publish_batch_rows WHERE batch_id=? ORDER BY row_no`, batchID)
|
||||
if err != nil {
|
||||
@@ -124,14 +122,12 @@ func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPu
|
||||
out := []ItemPublishBatchRow{}
|
||||
for rows.Next() {
|
||||
var r ItemPublishBatchRow
|
||||
var auto int
|
||||
if err := rows.Scan(&r.ID, &r.BatchID, &r.RowNo, &r.CookieID, &r.Title, &r.Description, &r.Price,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &auto, &r.CardGroupID,
|
||||
&r.DeliveryCount, &r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.RawJSON, &r.CreatedAt,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.AutomationJSON,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.RawJSON, &r.CreatedAt,
|
||||
&r.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.AutoCreateDeliveryRule = auto != 0
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
@@ -144,7 +140,7 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
|
||||
}
|
||||
rows, err := b.DB.QueryContext(ctx,
|
||||
`SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,auto_create_delivery_rule,card_group_id,delivery_count,status,item_id,item_url,error_message,
|
||||
images_json,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
raw_json,COALESCE(created_at,''),COALESCE(updated_at,'')
|
||||
FROM item_publish_batch_rows WHERE batch_id=? AND status IN `+statuses+` ORDER BY row_no`, batchID)
|
||||
if err != nil {
|
||||
@@ -154,14 +150,12 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
|
||||
out := []ItemPublishBatchRow{}
|
||||
for rows.Next() {
|
||||
var r ItemPublishBatchRow
|
||||
var auto int
|
||||
if err := rows.Scan(&r.ID, &r.BatchID, &r.RowNo, &r.CookieID, &r.Title, &r.Description, &r.Price,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &auto, &r.CardGroupID,
|
||||
&r.DeliveryCount, &r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.RawJSON, &r.CreatedAt,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.AutomationJSON,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.RawJSON, &r.CreatedAt,
|
||||
&r.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.AutoCreateDeliveryRule = auto != 0
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
-- +goose Up
|
||||
-- +goose StatementBegin
|
||||
-- 闲鱼管家全量 schema(从 Python db_manager.py 收敛)。
|
||||
-- 闲鱼管家初始 schema。
|
||||
-- 把历史上 12+ 处运行时 ALTER TABLE 补齐到 CREATE,并修复 schema 不一致:
|
||||
-- - orders.system_shipped:原 CREATE 缺失却被 insert_or_update_order 引用 → 补齐
|
||||
-- - orders.receiver_city:原为运行时补齐 → 补齐
|
||||
|
||||
@@ -29,7 +29,7 @@ type OrderRow struct {
|
||||
UpdatedAt string
|
||||
}
|
||||
|
||||
// OrdersByCookie 取某账号的订单(limit 上限)。移植自 get_orders_by_cookie。
|
||||
// ByCookie 取某账号的订单(limit 上限)。
|
||||
func (o *Orders) ByCookie(ctx context.Context, cookieID string, limit int) ([]OrderRow, error) {
|
||||
if limit <= 0 {
|
||||
limit = 1000
|
||||
@@ -71,7 +71,7 @@ func (o *Orders) ByCookie(ctx context.Context, cookieID string, limit int) ([]Or
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// OrderStatusMap 数字状态码 → 文本(移植自 Python order_status_handler)。
|
||||
// OrderStatusMap 将数字状态码转换为文本状态。
|
||||
var OrderStatusMap = map[string]string{
|
||||
"1": "processing", "2": "pending_ship", "3": "shipped", "4": "completed",
|
||||
"5": "refunding", "6": "cancelled", "7": "refunding", "8": "cancelled",
|
||||
@@ -89,7 +89,7 @@ func NormalizeOrderStatus(s string) string {
|
||||
return s
|
||||
}
|
||||
|
||||
// AllItemTitles 取全部 item_id → item_title 映射(订单列表用)。
|
||||
// AllTitles 取全部 item_id → item_title 映射(订单列表用)。
|
||||
func (i *Items) AllTitles(ctx context.Context) (map[string]string, error) {
|
||||
rows, err := i.DB.QueryContext(ctx, `SELECT item_id, item_title FROM item_info`)
|
||||
if err != nil {
|
||||
@@ -127,7 +127,7 @@ type CardFull struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
}
|
||||
|
||||
// GetCard 取单个卡券。
|
||||
// Get 取单个卡券。
|
||||
func (c *Cards) Get(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
var cf CardFull
|
||||
var enabled, isMultiSpec int
|
||||
@@ -156,7 +156,7 @@ func (c *Cards) Get(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
return &cf, nil
|
||||
}
|
||||
|
||||
// AllCardsForUser 取某用户全部卡券。
|
||||
// AllForUser 取某用户全部卡券。
|
||||
func (c *Cards) AllForUser(ctx context.Context, userID int64) ([]CardFull, error) {
|
||||
rows, err := c.DB.QueryContext(ctx,
|
||||
`SELECT id, name, type, api_config, text_content, data_content, image_url, description,
|
||||
@@ -189,7 +189,7 @@ func (c *Cards) AllForUser(ctx context.Context, userID int64) ([]CardFull, error
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// CreateCard 创建卡券,返回新 ID。
|
||||
// Create 创建卡券,返回新 ID。
|
||||
func (c *Cards) Create(ctx context.Context, cf *CardFull) (int64, error) {
|
||||
res, err := c.DB.ExecContext(ctx,
|
||||
`INSERT INTO cards (name, type, api_config, text_content, data_content, image_url, description,
|
||||
@@ -204,7 +204,7 @@ func (c *Cards) Create(ctx context.Context, cf *CardFull) (int64, error) {
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
// UpdateCard 更新卡券。
|
||||
// Update 更新卡券。
|
||||
func (c *Cards) Update(ctx context.Context, cf *CardFull) error {
|
||||
_, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cards SET name=?, type=?, api_config=?, text_content=?, data_content=?, image_url=?,
|
||||
@@ -216,7 +216,7 @@ func (c *Cards) Update(ctx context.Context, cf *CardFull) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteCard 删除卡券。
|
||||
// Delete 删除卡券。
|
||||
func (c *Cards) Delete(ctx context.Context, cardID int64) error {
|
||||
_, err := c.DB.ExecContext(ctx, `DELETE FROM cards WHERE id=?`, cardID)
|
||||
return err
|
||||
|
||||
@@ -21,7 +21,7 @@ func HashPassword(plain string) (string, error) {
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// legacySHA256 复刻 Python 端 hashlib.sha256(password).hexdigest(),用于兼容老库。
|
||||
// legacySHA256 兼容旧数据库中的 SHA-256 密码摘要。
|
||||
func legacySHA256(plain string) string {
|
||||
sum := sha256.Sum256([]byte(plain))
|
||||
return hex.EncodeToString(sum[:])
|
||||
@@ -36,6 +36,7 @@ func isLegacyHash(h string) bool {
|
||||
// VerifyPassword 校验明文与存储哈希。
|
||||
// - bcrypt 哈希:bcrypt.CompareHashAndPassword
|
||||
// - 老 SHA-256 哈希:逐字节对比(兼容老库)
|
||||
//
|
||||
// 返回 (matched, needsUpgrade)。needsUpgrade=true 表示命中老哈希、应升级到 bcrypt。
|
||||
func VerifyPassword(stored, plain string) (matched bool, needsUpgrade bool, err error) {
|
||||
if isLegacyHash(stored) {
|
||||
|
||||
@@ -80,8 +80,7 @@ func TestUserLifecycle(t *testing.T) {
|
||||
}
|
||||
|
||||
// 改密后旧密码失效。
|
||||
if _, _ = s.Users.UpdatePassword(ctx, "admin", "newpw"); true {
|
||||
}
|
||||
_, _ = s.Users.UpdatePassword(ctx, "admin", "newpw")
|
||||
_, okOld, _ := s.Users.VerifyAndUpgrade(ctx, "admin", "pw123")
|
||||
if okOld {
|
||||
t.Fatal("旧密码应失效")
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"encoding/base64"
|
||||
)
|
||||
|
||||
// SessionTTL 会话有效期(24 小时,与 Python SESSION_EXPIRE_SECONDS 一致)。
|
||||
// SessionTTL 是 24 小时的会话有效期。
|
||||
const SessionTTL = 24 * time.Hour
|
||||
|
||||
// Sessions 会话表操作(HttpOnly Cookie 会话)。
|
||||
@@ -81,7 +81,7 @@ func (s *Sessions) DeleteExpired(ctx context.Context) (int64, error) {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// randomSessionID 生成 URL 安全的随机会话 ID(对应 Python secrets.token_urlsafe(32))。
|
||||
// randomSessionID 生成 URL 安全的随机会话 ID。
|
||||
func randomSessionID() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
|
||||
@@ -19,7 +19,7 @@ type Users struct {
|
||||
}
|
||||
|
||||
// IsSystemInitialized 系统是否已初始化(至少存在 admin 用户)。
|
||||
// 对应 Python db_manager.is_system_initialized()。
|
||||
// IsSystemInitialized 判断系统是否已有管理员账号。
|
||||
func (u *Users) IsSystemInitialized(ctx context.Context) (bool, error) {
|
||||
var exists int
|
||||
err := u.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM users WHERE is_admin=1)`).Scan(&exists)
|
||||
@@ -36,7 +36,7 @@ func (u *Users) GetAdmin(ctx context.Context) (*User, error) {
|
||||
}
|
||||
|
||||
// Create 创建用户,密码用 bcrypt 哈希。
|
||||
// 用户名或邮箱重复时返回 false(对应 Python IntegrityError → return False)。
|
||||
// 用户名或邮箱重复时返回 false。
|
||||
func (u *Users) Create(ctx context.Context, username, email, plainPassword string) (bool, error) {
|
||||
hash, err := HashPassword(plainPassword)
|
||||
if err != nil {
|
||||
@@ -135,9 +135,9 @@ func (u *Users) UpdateCredentials(ctx context.Context, userID int64, username, p
|
||||
|
||||
var res sql.Result
|
||||
if plainPassword != "" {
|
||||
hash, err := HashPassword(plainPassword)
|
||||
if err != nil {
|
||||
return fmt.Errorf("哈希密码: %w", err)
|
||||
hash, hashErr := HashPassword(plainPassword)
|
||||
if hashErr != nil {
|
||||
return fmt.Errorf("哈希密码: %w", hashErr)
|
||||
}
|
||||
res, err = tx.ExecContext(ctx,
|
||||
`UPDATE users SET username=?, password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package logsafe
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRedactionHelpers(t *testing.T) {
|
||||
if ID(" secret ") != ID("secret") || len(ID("secret")) != 12 {
|
||||
t.Fatal("ID should be trimmed, stable, and short")
|
||||
}
|
||||
if ID("") != "" {
|
||||
t.Fatal("empty ID should remain empty")
|
||||
}
|
||||
if got := URL("https://example.com/path?q=token#secret"); got != "https://example.com/path" {
|
||||
t.Fatalf("URL leaked query or fragment: %q", got)
|
||||
}
|
||||
if got := URL("not-a-url"); got != "<redacted>" {
|
||||
t.Fatalf("invalid URL = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package notify 多渠道通知:dingtalk/feishu/lark/bark/webhook/wechat/telegram/email。
|
||||
// 移植自 Python _send_*_notification 系列。每个渠道解析 config JSON 后 POST。
|
||||
// 每个渠道解析 config JSON 后发送 HTTP 请求。
|
||||
// email 用 SMTP(net/smtp);其余为 HTTP POST。
|
||||
package notify
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// Notifier 通知发送器(实现 engine.Notifier 接口)。
|
||||
// Notifier 通知发送器。
|
||||
type Notifier struct {
|
||||
cookieID string
|
||||
store *db.Store
|
||||
@@ -43,14 +43,14 @@ func New(cookieID string, store *db.Store, logger *slog.Logger) *Notifier {
|
||||
}
|
||||
}
|
||||
|
||||
// NotifyDelivery 实现 engine.Notifier.NotifyDelivery。
|
||||
// NotifyDelivery 发送发货结果通知。
|
||||
// accountID 为 cookie_id。向该账号所有已启用渠道发送发货通知。
|
||||
func (n *Notifier) NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string) {
|
||||
channels, err := n.store.Notifications.AccountChannels(context.Background(), accountID)
|
||||
if err != nil || len(channels) == 0 {
|
||||
return
|
||||
}
|
||||
// 复刻 Python 通知文案。
|
||||
// 构造通知文案。
|
||||
body := fmt.Sprintf("🚨 自动发货通知\n\n账号: %s\n买家: %s (ID: %s)\n商品ID: %s\n聊天ID: %s\n结果: %s\n时间: %s\n\n请及时处理!",
|
||||
accountID, buyerName, buyerID, itemID, fallback(chatID, "未知"), message, time.Now().Format("2006-01-02 15:04:05"))
|
||||
for _, ch := range channels {
|
||||
@@ -131,8 +131,8 @@ func (n *Notifier) sendFeishu(cfg map[string]any, message string) error {
|
||||
}
|
||||
ts := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
data := map[string]any{
|
||||
"msg_type": "text",
|
||||
"content": map[string]any{"text": message},
|
||||
"msg_type": "text",
|
||||
"content": map[string]any{"text": message},
|
||||
"timestamp": ts,
|
||||
}
|
||||
if secret != "" {
|
||||
@@ -197,7 +197,9 @@ func (n *Notifier) sendWebhook(cfg map[string]any, message string) error {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("webhook 状态码 %d", resp.StatusCode)
|
||||
}
|
||||
@@ -270,7 +272,9 @@ func (n *Notifier) postJSON(url string, payload any) error {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("状态码 %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
@@ -71,9 +71,8 @@ func TestSendTelegram(t *testing.T) {
|
||||
cfg := map[string]any{"bot_token": "TOKEN", "chat_id": "123"}
|
||||
// 临时替换 httpc 的 URL:用 srv.URL 作为 webhook。sendTelegram 硬编码了 telegram API,
|
||||
// 这里改用 dingtalk server 验证 JSON 形状已覆盖;Telegram 单独验证配置校验。
|
||||
if err := n.sendTelegram(cfg, "hi"); err == nil {
|
||||
// 实际会尝试连 api.telegram.org,可能失败;仅验证不 panic。
|
||||
}
|
||||
// 实际会尝试连 api.telegram.org,可能失败;仅验证不 panic。
|
||||
_ = n.sendTelegram(cfg, "hi")
|
||||
// 配置不全应返回 error。
|
||||
if err := n.sendTelegram(map[string]any{"bot_token": ""}, "hi"); err == nil {
|
||||
t.Fatal("缺 chat_id 应报错")
|
||||
|
||||
@@ -29,12 +29,16 @@ func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) {
|
||||
var username, email, createdAt string
|
||||
var isActive, isAdmin int
|
||||
if err := rows.Scan(&id, &username, &email, &isActive, &isAdmin, &createdAt); err != nil {
|
||||
continue
|
||||
writeErr(w, http.StatusInternalServerError, "读取用户数据失败")
|
||||
return
|
||||
}
|
||||
// 统计每个用户的账号数。
|
||||
var cookieCount int
|
||||
s.Store.DB.QueryRowContext(r.Context(),
|
||||
`SELECT COUNT(*) FROM cookies WHERE user_id=?`, id).Scan(&cookieCount)
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(),
|
||||
`SELECT COUNT(*) FROM cookies WHERE user_id=?`, id).Scan(&cookieCount); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计用户账号失败")
|
||||
return
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": id, "username": username, "email": email,
|
||||
"is_active": isActive != 0, "is_admin": isAdmin != 0,
|
||||
@@ -79,7 +83,8 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
|
||||
var uid int64
|
||||
var remark, createdAt, username string
|
||||
if err := rows.Scan(&id, &uid, &remark, &createdAt, &username); err != nil {
|
||||
continue
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号数据失败")
|
||||
return
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": id, "user_id": uid, "remark": remark,
|
||||
@@ -94,25 +99,39 @@ func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) {
|
||||
// 字段名与前端 AdminStats 接口对齐:
|
||||
// total_users / total_cookies / active_cookies / total_cards / total_keywords / total_orders
|
||||
var totalUsers, totalCookies, totalCards, totalOrders, totalKeywords int64
|
||||
s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM users`).Scan(&totalUsers)
|
||||
s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM cookies`).Scan(&totalCookies)
|
||||
s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM cards`).Scan(&totalCards)
|
||||
s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM orders`).Scan(&totalOrders)
|
||||
s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM keywords`).Scan(&totalKeywords)
|
||||
counts := []struct {
|
||||
query string
|
||||
dest *int64
|
||||
}{
|
||||
{`SELECT COUNT(*) FROM users`, &totalUsers},
|
||||
{`SELECT COUNT(*) FROM cookies`, &totalCookies},
|
||||
{`SELECT COUNT(*) FROM cards`, &totalCards},
|
||||
{`SELECT COUNT(*) FROM orders`, &totalOrders},
|
||||
{`SELECT COUNT(*) FROM keywords`, &totalKeywords},
|
||||
}
|
||||
for _, count := range counts {
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), count.query).Scan(count.dest); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计数据失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 活跃账号:cookie_status.enabled=1 的数量(无记录默认启用,故统计 enabled=1 或无记录的)。
|
||||
var activeCookies int64
|
||||
s.Store.DB.QueryRowContext(r.Context(), `
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), `
|
||||
SELECT COUNT(*) FROM cookies c
|
||||
WHERE NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0)
|
||||
`).Scan(&activeCookies)
|
||||
`).Scan(&activeCookies); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计活跃账号失败")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]int64{
|
||||
"total_users": totalUsers,
|
||||
"total_cookies": totalCookies,
|
||||
"active_cookies": activeCookies,
|
||||
"total_cards": totalCards,
|
||||
"total_keywords": totalKeywords,
|
||||
"total_orders": totalOrders,
|
||||
"total_users": totalUsers,
|
||||
"total_cookies": totalCookies,
|
||||
"active_cookies": activeCookies,
|
||||
"total_cards": totalCards,
|
||||
"total_keywords": totalKeywords,
|
||||
"total_orders": totalOrders,
|
||||
})
|
||||
}
|
||||
@@ -15,11 +15,10 @@ func (s *Server) mountAnalyticsReal(r chi.Router) {
|
||||
r.Get("/analytics/orders/valid", s.validOrders)
|
||||
}
|
||||
|
||||
// 有效订单状态(只统计这几种,与 Python 一致)。
|
||||
// 有效订单状态只统计以下几种。
|
||||
var validOrderStatuses = []string{"pending_ship", "shipped", "completed"}
|
||||
|
||||
// orderAnalytics 订单分析:收益统计 + 按日/状态/城市/商品分布。
|
||||
// 移植自 Python get_order_analytics。
|
||||
// orderAnalytics 汇总指定日期范围内的收益以及按日、状态、城市和商品分布。
|
||||
func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
startDate := r.URL.Query().Get("start_date")
|
||||
@@ -39,11 +38,14 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
UniqueBuyers int
|
||||
UniqueItems int
|
||||
}
|
||||
s.Store.DB.QueryRowContext(r.Context(), `
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), `
|
||||
SELECT COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0),
|
||||
COALESCE(AVG(`+amountClean+`),0), COUNT(DISTINCT buyer_id), COUNT(DISTINCT item_id)
|
||||
FROM orders `+where+amountFilter, params...).Scan(
|
||||
&rev.TotalOrders, &rev.TotalAmount, &rev.AvgAmount, &rev.UniqueBuyers, &rev.UniqueItems)
|
||||
&rev.TotalOrders, &rev.TotalAmount, &rev.AvgAmount, &rev.UniqueBuyers, &rev.UniqueItems); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询收益统计失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 按日统计。
|
||||
daily := []map[string]any{}
|
||||
@@ -51,19 +53,21 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
SELECT DATE(created_at), COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0)
|
||||
FROM orders `+where+amountFilter+`
|
||||
GROUP BY DATE(created_at) ORDER BY DATE(created_at) DESC LIMIT 30`, params...)
|
||||
if err == nil {
|
||||
for rows.Next() {
|
||||
var date string
|
||||
var count int
|
||||
var amount float64
|
||||
if rows.Scan(&date, &count, &amount) == nil {
|
||||
daily = append(daily, map[string]any{
|
||||
"date": date, "order_count": count, "amount": round2(amount),
|
||||
})
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询每日统计失败")
|
||||
return
|
||||
}
|
||||
for rows.Next() {
|
||||
var date string
|
||||
var count int
|
||||
var amount float64
|
||||
if rows.Scan(&date, &count, &amount) == nil {
|
||||
daily = append(daily, map[string]any{
|
||||
"date": date, "order_count": count, "amount": round2(amount),
|
||||
})
|
||||
}
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
// 3. 按状态统计。
|
||||
statusStats := []map[string]any{}
|
||||
@@ -71,19 +75,21 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
SELECT COALESCE(order_status,'unknown'), COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0)
|
||||
FROM orders `+where+amountFilter+`
|
||||
GROUP BY order_status ORDER BY COUNT(DISTINCT order_id) DESC`, params...)
|
||||
if err == nil {
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var count int
|
||||
var amount float64
|
||||
if rows.Scan(&status, &count, &amount) == nil {
|
||||
statusStats = append(statusStats, map[string]any{
|
||||
"status": status, "count": count, "amount": round2(amount),
|
||||
})
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询状态统计失败")
|
||||
return
|
||||
}
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var count int
|
||||
var amount float64
|
||||
if rows.Scan(&status, &count, &amount) == nil {
|
||||
statusStats = append(statusStats, map[string]any{
|
||||
"status": status, "count": count, "amount": round2(amount),
|
||||
})
|
||||
}
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
// 4. 按城市统计。
|
||||
cityStats := []map[string]any{}
|
||||
@@ -92,19 +98,21 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
FROM orders `+where+amountFilter+`
|
||||
AND receiver_city IS NOT NULL AND receiver_city != ''
|
||||
GROUP BY receiver_city ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 50`, params...)
|
||||
if err == nil {
|
||||
for rows.Next() {
|
||||
var city string
|
||||
var count int
|
||||
var amount float64
|
||||
if rows.Scan(&city, &count, &amount) == nil {
|
||||
cityStats = append(cityStats, map[string]any{
|
||||
"city": city, "order_count": count, "total_amount": round2(amount),
|
||||
})
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询城市统计失败")
|
||||
return
|
||||
}
|
||||
for rows.Next() {
|
||||
var city string
|
||||
var count int
|
||||
var amount float64
|
||||
if rows.Scan(&city, &count, &amount) == nil {
|
||||
cityStats = append(cityStats, map[string]any{
|
||||
"city": city, "order_count": count, "total_amount": round2(amount),
|
||||
})
|
||||
}
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
// 5. 商品排行。
|
||||
itemStats := []map[string]any{}
|
||||
@@ -113,20 +121,22 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
FROM orders `+where+amountFilter+`
|
||||
AND item_id IS NOT NULL AND item_id != ''
|
||||
GROUP BY item_id ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 20`, params...)
|
||||
if err == nil {
|
||||
for rows.Next() {
|
||||
var itemID string
|
||||
var count int
|
||||
var total, avg float64
|
||||
if rows.Scan(&itemID, &count, &total, &avg) == nil {
|
||||
itemStats = append(itemStats, map[string]any{
|
||||
"item_id": itemID, "order_count": count,
|
||||
"total_amount": round2(total), "avg_amount": round2(avg),
|
||||
})
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询商品统计失败")
|
||||
return
|
||||
}
|
||||
for rows.Next() {
|
||||
var itemID string
|
||||
var count int
|
||||
var total, avg float64
|
||||
if rows.Scan(&itemID, &count, &total, &avg) == nil {
|
||||
itemStats = append(itemStats, map[string]any{
|
||||
"item_id": itemID, "order_count": count,
|
||||
"total_amount": round2(total), "avg_amount": round2(avg),
|
||||
})
|
||||
}
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"revenue_stats": map[string]any{
|
||||
@@ -134,10 +144,10 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
"avg_amount": round2(rev.AvgAmount), "unique_buyers": rev.UniqueBuyers,
|
||||
"unique_items": rev.UniqueItems,
|
||||
},
|
||||
"daily_stats": daily,
|
||||
"status_stats": statusStats,
|
||||
"city_stats": cityStats,
|
||||
"item_stats": itemStats,
|
||||
"daily_stats": daily,
|
||||
"status_stats": statusStats,
|
||||
"city_stats": cityStats,
|
||||
"item_stats": itemStats,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -147,10 +157,15 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
|
||||
startDate := r.URL.Query().Get("start_date")
|
||||
endDate := r.URL.Query().Get("end_date")
|
||||
where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses)
|
||||
amountFilter := ` AND orders.amount IS NOT NULL AND orders.amount != '' AND orders.amount != 'N/A'`
|
||||
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(), `
|
||||
SELECT order_id, item_id, buyer_id, amount, order_status, cookie_id, created_at
|
||||
FROM orders `+where+` ORDER BY created_at DESC LIMIT 500`, params...)
|
||||
SELECT orders.order_id, orders.item_id, COALESCE(item_info.item_title, ''),
|
||||
COALESCE(item_info.item_detail, ''), orders.buyer_id, COALESCE(orders.quantity, '1'),
|
||||
orders.amount, orders.order_status, orders.cookie_id, orders.created_at
|
||||
FROM orders
|
||||
LEFT JOIN item_info ON item_info.cookie_id = orders.cookie_id AND item_info.item_id = orders.item_id
|
||||
`+qualifyAnalyticsWhere(where)+amountFilter+` ORDER BY orders.created_at DESC LIMIT 500`, params...)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
@@ -158,16 +173,23 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
|
||||
defer rows.Close()
|
||||
out := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var orderID, itemID, buyerID, amount, status, cookieID, createdAt string
|
||||
if rows.Scan(&orderID, &itemID, &buyerID, &amount, &status, &cookieID, &createdAt) == nil {
|
||||
var orderID, itemID, itemTitle, itemDetail, buyerID, quantity, amount, status, cookieID, createdAt string
|
||||
if rows.Scan(&orderID, &itemID, &itemTitle, &itemDetail, &buyerID, &quantity, &amount, &status, &cookieID, &createdAt) == nil {
|
||||
out = append(out, map[string]any{
|
||||
"order_id": orderID, "item_id": itemID, "buyer_id": buyerID,
|
||||
"amount": amount, "order_status": status, "cookie_id": cookieID,
|
||||
"created_at": createdAt,
|
||||
"item_title": itemTitle, "item_image": itemImageFromDetail(itemDetail),
|
||||
"quantity": quantity, "amount": amount, "order_status": status,
|
||||
"status": status, "cookie_id": cookieID, "created_at": createdAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"orders": out})
|
||||
}
|
||||
|
||||
func qualifyAnalyticsWhere(where string) string {
|
||||
where = strings.ReplaceAll(where, "DATE(created_at)", "DATE(orders.created_at)")
|
||||
where = strings.ReplaceAll(where, "order_status IN", "orders.order_status IN")
|
||||
return where
|
||||
}
|
||||
|
||||
// buildAnalyticsWhere 构建 WHERE 子句(user_id 经 cookies 关联过滤 + 日期 + 状态)。
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = store.DB.ExecContext(ctx, `
|
||||
INSERT INTO orders (order_id, item_id, buyer_id, quantity, amount, order_status, cookie_id, created_at) VALUES
|
||||
('ord-valid', 'item1', 'buyer1', '2', '¥12.50', 'pending_ship', 'acc1', '2026-06-28 10:00:00'),
|
||||
('ord-no-amount', 'item1', 'buyer2', '1', '', 'pending_ship', 'acc1', '2026-06-28 10:00:00'),
|
||||
('ord-bad-status', 'item1', 'buyer3', '1', '9.90', 'cancelled', 'acc1', '2026-06-28 10:00:00')
|
||||
`)
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_detail) VALUES ('acc1','item1','测试商品','{"pic_info":{"picUrl":"https://img.example/item.png"}}')`)
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-06-28&end_date=2026-06-28", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("analytics status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var analytics struct {
|
||||
RevenueStats struct {
|
||||
TotalOrders int `json:"total_orders"`
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
} `json:"revenue_stats"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &analytics); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if analytics.RevenueStats.TotalOrders != 1 || analytics.RevenueStats.TotalAmount != 12.5 {
|
||||
t.Fatalf("统计口径异常: %+v", analytics.RevenueStats)
|
||||
}
|
||||
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-06-28&end_date=2026-06-28", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != http.StatusOK {
|
||||
t.Fatalf("valid orders status=%d body=%s", rec2.Code, rec2.Body.String())
|
||||
}
|
||||
var valid struct {
|
||||
Orders []map[string]any `json:"orders"`
|
||||
}
|
||||
if err := json.Unmarshal(rec2.Body.Bytes(), &valid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(valid.Orders) != 1 {
|
||||
t.Fatalf("有效订单明细数量应与统计订单数一致,got %d body=%s", len(valid.Orders), rec2.Body.String())
|
||||
}
|
||||
order := valid.Orders[0]
|
||||
if order["order_id"] != "ord-valid" || order["item_title"] != "测试商品" || !strings.Contains(order["item_image"].(string), "img.example") {
|
||||
t.Fatalf("有效订单明细字段异常: %+v", order)
|
||||
}
|
||||
if order["status"] != "pending_ship" || order["order_status"] != "pending_ship" {
|
||||
t.Fatalf("状态字段异常: %+v", order)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// loginRequest 对应 Python LoginRequest。
|
||||
// loginRequest 是登录请求体。
|
||||
type loginRequest struct {
|
||||
Username string `json:"username,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
@@ -18,7 +18,7 @@ type loginRequest struct {
|
||||
VerificationCode string `json:"verification_code,omitempty"`
|
||||
}
|
||||
|
||||
// loginResponse 对应 Python LoginResponse。
|
||||
// loginResponse 是登录响应体。
|
||||
type loginResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Token *string `json:"token"`
|
||||
|
||||
@@ -3,7 +3,6 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -290,8 +289,11 @@ func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
if req.AutoConfirm {
|
||||
v = 1
|
||||
}
|
||||
s.Store.DB.ExecContext(r.Context(),
|
||||
`UPDATE cookies SET auto_confirm=? WHERE id=?`, v, cid)
|
||||
if _, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`UPDATE cookies SET auto_confirm=? WHERE id=?`, v, cid); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存自动确认设置失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
@@ -316,8 +318,11 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
s.Store.DB.ExecContext(r.Context(),
|
||||
`UPDATE cookies SET remark=? WHERE id=?`, req.Remark, cid)
|
||||
if _, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`UPDATE cookies SET remark=? WHERE id=?`, req.Remark, cid); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存账号备注失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
@@ -331,8 +336,15 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
s.Store.DB.ExecContext(r.Context(),
|
||||
`UPDATE cookies SET pause_duration=? WHERE id=?`, req.PauseDuration, cid)
|
||||
if req.PauseDuration < 0 {
|
||||
writeErr(w, http.StatusBadRequest, "暂停时长不能为负数")
|
||||
return
|
||||
}
|
||||
if _, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`UPDATE cookies SET pause_duration=? WHERE id=?`, req.PauseDuration, cid); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存暂停时长失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
@@ -389,10 +401,6 @@ func cachedAccountNickname(d *db.CookieDetail) string {
|
||||
return "账号 " + truncate(d.ID, 6)
|
||||
}
|
||||
|
||||
func accountProfileFallback(d *db.CookieDetail) string {
|
||||
return fallback(d.Remark, "账号 "+truncate(d.ID, 6))
|
||||
}
|
||||
|
||||
func normalizeProfileAvatarURL(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
@@ -413,5 +421,3 @@ func truncate(s string, n int) string {
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
func atoi(s string) int { n, _ := strconv.Atoi(s); return n }
|
||||
@@ -12,7 +12,7 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
// errDetail 构造 {"detail": msg} 错误体(与 Python FastAPI 默认错误格式一致)。
|
||||
// errDetail 构造 {"detail": msg} 错误体。
|
||||
func errDetail(msg string) map[string]any {
|
||||
return map[string]any{"detail": msg}
|
||||
}
|
||||
@@ -27,11 +27,3 @@ func decodeJSON(r *http.Request, v any) error {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
return dec.Decode(v)
|
||||
}
|
||||
|
||||
// fallback 空字符串返回默认值。
|
||||
func fallback(s, def string) string {
|
||||
if s == "" {
|
||||
return def
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -40,6 +40,9 @@ func (s *Server) mountItemsReal(r chi.Router) {
|
||||
}
|
||||
|
||||
func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
// 最多 9 张 10 MiB 图片,额外预留 multipart 元数据空间。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 96<<20)
|
||||
// #nosec G120 -- 请求体已由 MaxBytesReader 限制为 96 MiB。
|
||||
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误,请使用 multipart/form-data")
|
||||
return
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -23,6 +24,7 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
@@ -30,39 +32,64 @@ import (
|
||||
const maxPublishBatchRows = 50
|
||||
|
||||
type publishBatchPreviewRow struct {
|
||||
RowNo int `json:"row_no"`
|
||||
Valid bool `json:"valid"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
CookieID string `json:"cookie_id"`
|
||||
Title string `json:"title"`
|
||||
Price string `json:"price"`
|
||||
Quantity int `json:"quantity"`
|
||||
Images []string `json:"images"`
|
||||
AutoCreateDeliveryRule bool `json:"auto_create_delivery_rule"`
|
||||
CardGroupID int64 `json:"card_group_id"`
|
||||
DeliveryCount int `json:"delivery_count"`
|
||||
RowNo int `json:"row_no"`
|
||||
Valid bool `json:"valid"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
CookieID string `json:"cookie_id"`
|
||||
Title string `json:"title"`
|
||||
Price string `json:"price"`
|
||||
Quantity int `json:"quantity"`
|
||||
Images []string `json:"images"`
|
||||
Automation publishAutomationConfig `json:"automation"`
|
||||
}
|
||||
|
||||
type publishBatchParsedRow struct {
|
||||
RowNo int
|
||||
CookieID string
|
||||
Title string
|
||||
Description string
|
||||
Price string
|
||||
OriginalPrice string
|
||||
Quantity int
|
||||
PostageMode string
|
||||
Postage string
|
||||
Images []string
|
||||
AutoCreateDeliveryRule bool
|
||||
CardGroupID int64
|
||||
DeliveryCount int
|
||||
Errors []string
|
||||
Raw map[string]any
|
||||
RowNo int
|
||||
CookieID string
|
||||
Title string
|
||||
Description string
|
||||
Price string
|
||||
OriginalPrice string
|
||||
Quantity int
|
||||
PostageMode string
|
||||
Postage string
|
||||
Images []string
|
||||
Automation publishAutomationConfig
|
||||
Errors []string
|
||||
Raw map[string]any
|
||||
}
|
||||
|
||||
type publishAutomationConfig struct {
|
||||
PaidDelivery publishCardAutomation `json:"paid_delivery"`
|
||||
ReviewGift publishCardAutomation `json:"review_gift"`
|
||||
ReviewRequest publishReviewRequestCfg `json:"review_request"`
|
||||
}
|
||||
|
||||
type publishCardAutomation struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Actions []publishCardAction `json:"actions"`
|
||||
ParseError string `json:"-"`
|
||||
}
|
||||
|
||||
type publishCardAction struct {
|
||||
CardID int64 `json:"card_id"`
|
||||
DeliveryCount int `json:"delivery_count"`
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
}
|
||||
|
||||
type publishReviewRequestCfg struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
AfterShippedHours int `json:"after_shipped_hours"`
|
||||
Message string `json:"message"`
|
||||
MaxAttempts int `json:"max_attempts"`
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
}
|
||||
|
||||
func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// 表格最大 20 MiB,图片压缩包最大 200 MiB,额外预留 multipart 元数据空间。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 224<<20)
|
||||
// #nosec G120 -- 请求体已由 MaxBytesReader 限制为 224 MiB。
|
||||
if err := r.ParseMultipartForm(256 << 20); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "解析上传文件失败")
|
||||
return
|
||||
@@ -85,7 +112,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
batchID := "batch_" + randomHex(12)
|
||||
uploadDir := filepath.Join(s.publishUploadRoot(), "publish_batches", batchID)
|
||||
if err := os.MkdirAll(uploadDir, 0o755); err != nil {
|
||||
if err := os.MkdirAll(uploadDir, 0o750); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "创建上传目录失败")
|
||||
return
|
||||
}
|
||||
@@ -93,7 +120,10 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
if sourceName == "" {
|
||||
sourceName = "products.csv"
|
||||
}
|
||||
_ = os.WriteFile(filepath.Join(uploadDir, sourceName), sourceBytes, 0o644)
|
||||
if err := writeFileWithinRoot(uploadDir, sourceName, sourceBytes); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存商品表格失败")
|
||||
return
|
||||
}
|
||||
|
||||
if zipFile, zipHeader, err := r.FormFile("images_zip"); err == nil {
|
||||
defer zipFile.Close()
|
||||
@@ -106,7 +136,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
if zipName == "" {
|
||||
zipName = "images.zip"
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(uploadDir, zipName), zipBytes, 0o644); err != nil {
|
||||
if err := writeFileWithinRoot(uploadDir, zipName, zipBytes); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存图片 zip 失败")
|
||||
return
|
||||
}
|
||||
@@ -137,6 +167,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
invalid++
|
||||
}
|
||||
imagesJSON, _ := json.Marshal(p.Images)
|
||||
automationJSON, _ := json.Marshal(p.Automation)
|
||||
rawJSON, _ := json.Marshal(p.Raw)
|
||||
status := "pending"
|
||||
errMsg := ""
|
||||
@@ -145,35 +176,31 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
errMsg = strings.Join(p.Errors, ";")
|
||||
}
|
||||
rows = append(rows, db.ItemPublishBatchRow{
|
||||
RowNo: p.RowNo,
|
||||
CookieID: p.CookieID,
|
||||
Title: p.Title,
|
||||
Description: p.Description,
|
||||
Price: p.Price,
|
||||
OriginalPrice: p.OriginalPrice,
|
||||
Quantity: p.Quantity,
|
||||
PostageMode: p.PostageMode,
|
||||
Postage: p.Postage,
|
||||
ImagesJSON: string(imagesJSON),
|
||||
AutoCreateDeliveryRule: p.AutoCreateDeliveryRule,
|
||||
CardGroupID: p.CardGroupID,
|
||||
DeliveryCount: p.DeliveryCount,
|
||||
Status: status,
|
||||
ErrorMessage: errMsg,
|
||||
RawJSON: string(rawJSON),
|
||||
RowNo: p.RowNo,
|
||||
CookieID: p.CookieID,
|
||||
Title: p.Title,
|
||||
Description: p.Description,
|
||||
Price: p.Price,
|
||||
OriginalPrice: p.OriginalPrice,
|
||||
Quantity: p.Quantity,
|
||||
PostageMode: p.PostageMode,
|
||||
Postage: p.Postage,
|
||||
ImagesJSON: string(imagesJSON),
|
||||
AutomationJSON: string(automationJSON),
|
||||
Status: status,
|
||||
ErrorMessage: errMsg,
|
||||
RawJSON: string(rawJSON),
|
||||
})
|
||||
previewRows = append(previewRows, publishBatchPreviewRow{
|
||||
RowNo: p.RowNo,
|
||||
Valid: isValid,
|
||||
Errors: p.Errors,
|
||||
CookieID: p.CookieID,
|
||||
Title: p.Title,
|
||||
Price: p.Price,
|
||||
Quantity: p.Quantity,
|
||||
Images: p.Images,
|
||||
AutoCreateDeliveryRule: p.AutoCreateDeliveryRule,
|
||||
CardGroupID: p.CardGroupID,
|
||||
DeliveryCount: p.DeliveryCount,
|
||||
RowNo: p.RowNo,
|
||||
Valid: isValid,
|
||||
Errors: p.Errors,
|
||||
CookieID: p.CookieID,
|
||||
Title: p.Title,
|
||||
Price: p.Price,
|
||||
Quantity: p.Quantity,
|
||||
Images: p.Images,
|
||||
Automation: p.Automation,
|
||||
})
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
@@ -242,7 +269,12 @@ func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "启动任务失败")
|
||||
return
|
||||
}
|
||||
go s.runItemPublishBatch(context.Background(), sess.UserID, batch.ID, false)
|
||||
// #nosec G118 -- 批处理必须在请求结束后继续,并由 30 分钟超时保证退出。
|
||||
go func() {
|
||||
jobCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
defer cancel()
|
||||
s.runItemPublishBatch(jobCtx, sess.UserID, batch.ID, false)
|
||||
}()
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batch.ID})
|
||||
}
|
||||
|
||||
@@ -292,7 +324,12 @@ func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Requ
|
||||
writeErr(w, http.StatusInternalServerError, "启动重试失败")
|
||||
return
|
||||
}
|
||||
go s.runItemPublishBatch(context.Background(), sess.UserID, batchID, false)
|
||||
// #nosec G118 -- 批处理必须在请求结束后继续,并由 30 分钟超时保证退出。
|
||||
go func() {
|
||||
jobCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
defer cancel()
|
||||
s.runItemPublishBatch(jobCtx, sess.UserID, batchID, false)
|
||||
}()
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batchID})
|
||||
}
|
||||
|
||||
@@ -431,35 +468,65 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client *mtop
|
||||
ItemDetail: string(detailJSON),
|
||||
MultiQuantityDelivery: row.Quantity > 1,
|
||||
})
|
||||
if row.AutoCreateDeliveryRule && row.CardGroupID > 0 {
|
||||
_ = s.createPublishDeliveryRule(ctx, userID, row, res)
|
||||
}
|
||||
_ = s.createPublishAutomationRules(ctx, userID, row, res)
|
||||
}
|
||||
rawJSON, _ := json.Marshal(res.RawData)
|
||||
return s.Store.PublishBatches.MarkRowSuccess(ctx, row.ID, res.ItemID, res.ItemURL, string(rawJSON))
|
||||
}
|
||||
|
||||
func (s *Server) createPublishDeliveryRule(ctx context.Context, userID int64, row db.ItemPublishBatchRow, res *mtop.PublishItemResult) error {
|
||||
tx, err := s.Store.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
func (s *Server) createPublishAutomationRules(ctx context.Context, userID int64, row db.ItemPublishBatchRow, res *mtop.PublishItemResult) error {
|
||||
var cfg publishAutomationConfig
|
||||
if err := json.Unmarshal([]byte(row.AutomationJSON), &cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
req := []deliveryVariantRequest{{CardID: row.CardGroupID, DeliveryCount: row.DeliveryCount}}
|
||||
ruleRes, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO delivery_rules
|
||||
(keyword,card_id,delivery_count,enabled,description,user_id,cookie_id,item_id)
|
||||
VALUES (?,?,?,?,?,?,?,?)`,
|
||||
firstNonEmpty(res.Title, row.Title), row.CardGroupID, row.DeliveryCount, true, "批量铺货自动创建",
|
||||
userID, row.CookieID, res.ItemID)
|
||||
if err != nil {
|
||||
return err
|
||||
title := firstNonEmpty(res.Title, row.Title)
|
||||
if cfg.PaidDelivery.Enabled {
|
||||
actions := make([]db.AutomationActionInput, 0, len(cfg.PaidDelivery.Actions)+1)
|
||||
for index, action := range cfg.PaidDelivery.Actions {
|
||||
actions = append(actions, db.AutomationActionInput{
|
||||
ActionType: automation.ActionSendCard, CardID: action.CardID,
|
||||
DeliveryCount: action.DeliveryCount, DelaySeconds: action.DelaySeconds,
|
||||
Enabled: true, SortOrder: index + 1,
|
||||
})
|
||||
}
|
||||
actions = append(actions, db.AutomationActionInput{
|
||||
ActionType: automation.ActionConfirmShipment, Enabled: true, SortOrder: len(actions) + 1,
|
||||
})
|
||||
_, _ = s.Store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: userID, CookieID: row.CookieID, ItemID: res.ItemID,
|
||||
Name: "付款后自动发货 - " + title, TriggerType: automation.TriggerOrderPaid,
|
||||
Enabled: true, Priority: 100, ConfigJSON: "{}",
|
||||
Actions: actions,
|
||||
})
|
||||
}
|
||||
ruleID, _ := ruleRes.LastInsertId()
|
||||
if err := insertDeliveryVariants(ctx, tx, userID, ruleID, req); err != nil {
|
||||
return err
|
||||
if cfg.ReviewGift.Enabled {
|
||||
actions := make([]db.AutomationActionInput, 0, len(cfg.ReviewGift.Actions))
|
||||
for index, action := range cfg.ReviewGift.Actions {
|
||||
actions = append(actions, db.AutomationActionInput{
|
||||
ActionType: automation.ActionSendCard, CardID: action.CardID,
|
||||
DeliveryCount: action.DeliveryCount, DelaySeconds: action.DelaySeconds,
|
||||
Enabled: true, SortOrder: index + 1,
|
||||
})
|
||||
}
|
||||
_, _ = s.Store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: userID, CookieID: row.CookieID, ItemID: res.ItemID,
|
||||
Name: "评价后发送赠品 - " + title, TriggerType: automation.TriggerBuyerReviewed,
|
||||
Enabled: true, Priority: 100, ConfigJSON: "{}",
|
||||
Actions: actions,
|
||||
})
|
||||
}
|
||||
return tx.Commit()
|
||||
if cfg.ReviewRequest.Enabled {
|
||||
cfgJSON, _ := json.Marshal(map[string]any{"after_shipped_hours": cfg.ReviewRequest.AfterShippedHours, "max_attempts": cfg.ReviewRequest.MaxAttempts})
|
||||
_, _ = s.Store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: userID, CookieID: row.CookieID, ItemID: res.ItemID,
|
||||
Name: "超时未评价求评价 - " + title, TriggerType: automation.TriggerReviewMissingTimeout,
|
||||
Enabled: true, Priority: 100, ConfigJSON: string(cfgJSON),
|
||||
Actions: []db.AutomationActionInput{
|
||||
{ActionType: automation.ActionSendText, MessageTemplate: cfg.ReviewRequest.Message, DelaySeconds: cfg.ReviewRequest.DelaySeconds, Enabled: true, SortOrder: 1},
|
||||
},
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCookieID, uploadDir string, input []map[string]any) []publishBatchParsedRow {
|
||||
@@ -493,9 +560,7 @@ func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCook
|
||||
row.PostageMode = "fixed"
|
||||
}
|
||||
row.Quantity = atoiPublishDefault(firstImportString(m, "quantity", "库存", "数量"), 1)
|
||||
row.DeliveryCount = atoiPublishDefault(firstImportString(m, "delivery_count", "发货数量"), 1)
|
||||
row.CardGroupID = int64(atoiPublishDefault(firstImportString(m, "card_group_id", "卡密组ID", "卡密组id", "卡密ID", "卡密id"), 0))
|
||||
row.AutoCreateDeliveryRule = parseLooseBool(firstImportString(m, "auto_create_delivery_rule", "自动创建发货规则"))
|
||||
row.Automation = parsePublishAutomation(m)
|
||||
row.Images = splitImageRefs(firstImportString(m, "images", "image", "图片", "商品图片"))
|
||||
if row.CookieID == "" {
|
||||
row.Errors = append(row.Errors, "缺少账号ID")
|
||||
@@ -530,21 +595,116 @@ func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCook
|
||||
row.Errors = append(row.Errors, err.Error())
|
||||
}
|
||||
}
|
||||
if row.AutoCreateDeliveryRule {
|
||||
if row.CardGroupID <= 0 {
|
||||
row.Errors = append(row.Errors, "自动创建发货规则需要填写卡密组ID")
|
||||
} else if !s.cardOwnedByUser(ctx, userID, row.CardGroupID) {
|
||||
row.Errors = append(row.Errors, "卡密组不存在或不属于当前用户")
|
||||
}
|
||||
if row.DeliveryCount <= 0 {
|
||||
row.Errors = append(row.Errors, "发货数量必须大于 0")
|
||||
}
|
||||
}
|
||||
row.Errors = append(row.Errors, s.validatePublishAutomation(ctx, userID, row.Automation)...)
|
||||
out = append(out, row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func parsePublishAutomation(m map[string]any) publishAutomationConfig {
|
||||
cfg := publishAutomationConfig{}
|
||||
paidActions, paidParseErr := parsePublishCardActions(firstImportString(m, "paid_delivery_contents", "付款发货内容"))
|
||||
cfg.PaidDelivery = publishCardAutomation{
|
||||
Enabled: parseLooseBool(firstImportString(m, "paid_delivery_enabled", "付款发货启用")),
|
||||
Actions: paidActions,
|
||||
ParseError: paidParseErr,
|
||||
}
|
||||
reviewGiftActions, reviewGiftParseErr := parsePublishCardActions(firstImportString(m, "review_gift_contents", "评价赠品内容"))
|
||||
cfg.ReviewGift = publishCardAutomation{
|
||||
Enabled: parseLooseBool(firstImportString(m, "review_gift_enabled", "评价赠品启用")),
|
||||
Actions: reviewGiftActions,
|
||||
ParseError: reviewGiftParseErr,
|
||||
}
|
||||
cfg.ReviewRequest = publishReviewRequestCfg{
|
||||
Enabled: parseLooseBool(firstImportString(m, "review_request_enabled", "求评价启用")),
|
||||
AfterShippedHours: atoiPublishDefault(firstImportString(m, "review_request_after_hours", "求评价等待小时"), 72),
|
||||
Message: firstImportString(m, "review_request_message", "求评价文案"),
|
||||
MaxAttempts: atoiPublishDefault(firstImportString(m, "review_request_max_attempts", "求评价最多次数"), 1),
|
||||
DelaySeconds: atoiPublishDefault(firstImportString(m, "review_request_delay_seconds", "求评价延迟秒"), 0),
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// parsePublishCardActions 解析“卡密组ID:每件份数:延迟秒”,多条内容用分号或换行分隔。
|
||||
func parsePublishCardActions(raw string) ([]publishCardAction, string) {
|
||||
entries := strings.FieldsFunc(strings.TrimSpace(raw), func(r rune) bool {
|
||||
return r == ';' || r == ';' || r == '\n' || r == '\r'
|
||||
})
|
||||
if len(entries) == 0 {
|
||||
return nil, ""
|
||||
}
|
||||
actions := make([]publishCardAction, 0, len(entries))
|
||||
for index, entry := range entries {
|
||||
parts := strings.Split(strings.ReplaceAll(strings.TrimSpace(entry), ":", ":"), ":")
|
||||
if len(parts) < 1 || len(parts) > 3 || strings.TrimSpace(parts[0]) == "" {
|
||||
return nil, fmt.Sprintf("第%d项格式错误,应为 卡密组ID:每件份数:延迟秒", index+1)
|
||||
}
|
||||
cardID, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64)
|
||||
if err != nil || cardID <= 0 {
|
||||
return nil, fmt.Sprintf("第%d项卡密组ID无效", index+1)
|
||||
}
|
||||
count := 1
|
||||
if len(parts) >= 2 && strings.TrimSpace(parts[1]) != "" {
|
||||
count, err = strconv.Atoi(strings.TrimSpace(parts[1]))
|
||||
if err != nil || count <= 0 {
|
||||
return nil, fmt.Sprintf("第%d项每件份数必须大于0", index+1)
|
||||
}
|
||||
}
|
||||
delay := 0
|
||||
if len(parts) == 3 && strings.TrimSpace(parts[2]) != "" {
|
||||
delay, err = strconv.Atoi(strings.TrimSpace(parts[2]))
|
||||
if err != nil || delay < 0 {
|
||||
return nil, fmt.Sprintf("第%d项延迟秒不能小于0", index+1)
|
||||
}
|
||||
}
|
||||
actions = append(actions, publishCardAction{CardID: cardID, DeliveryCount: count, DelaySeconds: delay})
|
||||
}
|
||||
return actions, ""
|
||||
}
|
||||
|
||||
func (s *Server) validatePublishAutomation(ctx context.Context, userID int64, cfg publishAutomationConfig) []string {
|
||||
var errs []string
|
||||
validateCards := func(config publishCardAutomation, label string) {
|
||||
if !config.Enabled {
|
||||
return
|
||||
}
|
||||
if config.ParseError != "" {
|
||||
errs = append(errs, label+config.ParseError)
|
||||
return
|
||||
}
|
||||
if len(config.Actions) == 0 {
|
||||
errs = append(errs, label+"需要至少配置一条发货内容")
|
||||
return
|
||||
}
|
||||
for index, action := range config.Actions {
|
||||
prefix := fmt.Sprintf("%s第%d项", label, index+1)
|
||||
if !s.cardOwnedByUser(ctx, userID, action.CardID) {
|
||||
errs = append(errs, prefix+"卡密组不存在或不属于当前用户")
|
||||
}
|
||||
if action.DeliveryCount <= 0 {
|
||||
errs = append(errs, prefix+"每件份数必须大于0")
|
||||
}
|
||||
if action.DelaySeconds < 0 {
|
||||
errs = append(errs, prefix+"延迟秒不能小于0")
|
||||
}
|
||||
}
|
||||
}
|
||||
validateCards(cfg.PaidDelivery, "付款发货")
|
||||
validateCards(cfg.ReviewGift, "评价赠品")
|
||||
if cfg.ReviewRequest.Enabled {
|
||||
if cfg.ReviewRequest.AfterShippedHours <= 0 {
|
||||
errs = append(errs, "求评价等待小时必须大于 0")
|
||||
}
|
||||
if strings.TrimSpace(cfg.ReviewRequest.Message) == "" {
|
||||
errs = append(errs, "求评价文案不能为空")
|
||||
}
|
||||
if cfg.ReviewRequest.MaxAttempts <= 0 {
|
||||
errs = append(errs, "求评价最多次数必须大于 0")
|
||||
}
|
||||
}
|
||||
return errs
|
||||
}
|
||||
|
||||
func parsePublishSheetBytes(raw []byte, filename string) ([]map[string]any, error) {
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return nil, fmt.Errorf("导入内容为空")
|
||||
@@ -669,12 +829,24 @@ func normalizePublishHeader(header string) string {
|
||||
return "postage"
|
||||
case "images", "image", "图片", "商品图片":
|
||||
return "images"
|
||||
case "autocreatedeliveryrule", "自动创建发货规则":
|
||||
return "auto_create_delivery_rule"
|
||||
case "cardgroupid", "cardid", "卡密组id", "卡密id":
|
||||
return "card_group_id"
|
||||
case "deliverycount", "发货数量":
|
||||
return "delivery_count"
|
||||
case "paiddeliveryenabled", "付款发货启用", "付款后自动发货":
|
||||
return "paid_delivery_enabled"
|
||||
case "paiddeliverycontents", "付款发货内容", "付款后发送的卡密":
|
||||
return "paid_delivery_contents"
|
||||
case "reviewgiftenabled", "评价赠品启用", "评价后发送赠品":
|
||||
return "review_gift_enabled"
|
||||
case "reviewgiftcontents", "评价赠品内容", "评价后发送的卡密":
|
||||
return "review_gift_contents"
|
||||
case "reviewrequestenabled", "求评价启用", "超时未评价时提醒":
|
||||
return "review_request_enabled"
|
||||
case "reviewrequestafterhours", "求评价等待小时", "发货几小时后提醒":
|
||||
return "review_request_after_hours"
|
||||
case "reviewrequestmessage", "求评价文案", "提醒内容":
|
||||
return "review_request_message"
|
||||
case "reviewrequestmaxattempts", "求评价最多次数", "最多提醒几次":
|
||||
return "review_request_max_attempts"
|
||||
case "reviewrequestdelayseconds", "求评价延迟秒":
|
||||
return "review_request_delay_seconds"
|
||||
default:
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
@@ -693,11 +865,12 @@ func extractPublishImagesZip(raw []byte, dest string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target := filepath.Join(dest, rel)
|
||||
if !strings.HasPrefix(target, filepath.Clean(dest)+string(os.PathSeparator)) {
|
||||
return fmt.Errorf("zip 内路径不安全: %s", f.Name)
|
||||
root, err := os.OpenRoot(dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
||||
if err := root.MkdirAll(filepath.Dir(rel), 0o750); err != nil {
|
||||
_ = root.Close()
|
||||
return err
|
||||
}
|
||||
rc, err := f.Open()
|
||||
@@ -715,7 +888,16 @@ func extractPublishImagesZip(raw []byte, dest string) error {
|
||||
if !strings.HasPrefix(http.DetectContentType(data), "image/") {
|
||||
continue
|
||||
}
|
||||
if err := os.WriteFile(target, data, 0o644); err != nil {
|
||||
file, err := root.OpenFile(rel, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
|
||||
if err == nil {
|
||||
_, err = file.Write(data)
|
||||
closeErr := file.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}
|
||||
_ = root.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -755,11 +937,20 @@ func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
|
||||
if err != nil {
|
||||
return nil, "", "", err
|
||||
}
|
||||
path := filepath.Join(uploadDir, rel)
|
||||
data, err := os.ReadFile(path)
|
||||
root, err := os.OpenRoot(uploadDir)
|
||||
if err != nil {
|
||||
return nil, "", "", fmt.Errorf("打开图片目录失败")
|
||||
}
|
||||
defer root.Close()
|
||||
file, err := root.Open(rel)
|
||||
if err != nil {
|
||||
return nil, "", "", fmt.Errorf("读取图片失败: %s", ref)
|
||||
}
|
||||
defer file.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
|
||||
if err != nil || len(data) > 10<<20 {
|
||||
return nil, "", "", fmt.Errorf("读取图片失败或文件过大: %s", ref)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, "", "", fmt.Errorf("图片文件为空: %s", ref)
|
||||
}
|
||||
@@ -770,12 +961,31 @@ func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
|
||||
return data, contentType, filepath.Base(rel), nil
|
||||
}
|
||||
|
||||
// writeFileWithinRoot 将上传文件限制在指定根目录内,拒绝符号链接和路径逃逸。
|
||||
func writeFileWithinRoot(rootDir, name string, data []byte) error {
|
||||
root, err := os.OpenRoot(rootDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
file, err := root.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := file.Write(data); err != nil {
|
||||
_ = file.Close()
|
||||
return err
|
||||
}
|
||||
return file.Close()
|
||||
}
|
||||
|
||||
func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
if err != nil || (req.URL.Scheme != "http" && req.URL.Scheme != "https") || req.URL.Hostname() == "" {
|
||||
return nil, "", fmt.Errorf("图片 URL 无效: %s", rawURL)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
client := publicHTTPClient()
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("下载图片失败: %s", rawURL)
|
||||
}
|
||||
@@ -783,10 +993,13 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, "", fmt.Errorf("下载图片失败: %s HTTP %d", rawURL, resp.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20))
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, (10<<20)+1))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("读取远程图片失败: %s", rawURL)
|
||||
}
|
||||
if len(data) > 10<<20 {
|
||||
return nil, "", fmt.Errorf("远程图片不能超过 10 MiB: %s", rawURL)
|
||||
}
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if i := strings.Index(contentType, ";"); i >= 0 {
|
||||
contentType = contentType[:i]
|
||||
@@ -800,6 +1013,48 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
|
||||
return data, contentType, nil
|
||||
}
|
||||
|
||||
// publicHTTPClient 只允许连接公网地址,防止批量铺货图片 URL 访问本机或内网服务。
|
||||
func publicHTTPClient() *http.Client {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
transport := &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, resolved := range ips {
|
||||
if isPublicIP(resolved.IP) {
|
||||
return dialer.DialContext(ctx, network, net.JoinHostPort(resolved.IP.String(), port))
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("拒绝访问非公网地址")
|
||||
},
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: 30 * time.Second,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 5 {
|
||||
return fmt.Errorf("图片 URL 重定向次数过多")
|
||||
}
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||
return fmt.Errorf("图片 URL 重定向协议不安全")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func isPublicIP(ip net.IP) bool {
|
||||
return ip != nil && !ip.IsLoopback() && !ip.IsPrivate() && !ip.IsLinkLocalUnicast() &&
|
||||
!ip.IsLinkLocalMulticast() && !ip.IsUnspecified() && !ip.IsMulticast()
|
||||
}
|
||||
|
||||
func validateBatchImageRef(uploadDir, ref string) error {
|
||||
if isHTTPURL(ref) {
|
||||
return nil
|
||||
@@ -829,12 +1084,13 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow
|
||||
}
|
||||
var refs []string
|
||||
_ = json.Unmarshal([]byte(row.ImagesJSON), &refs)
|
||||
var automationCfg publishAutomationConfig
|
||||
_ = json.Unmarshal([]byte(row.AutomationJSON), &automationCfg)
|
||||
outRows = append(outRows, map[string]any{
|
||||
"id": row.ID, "row_no": row.RowNo, "cookie_id": row.CookieID, "title": row.Title,
|
||||
"price": row.Price, "quantity": row.Quantity, "images": refs,
|
||||
"auto_create_delivery_rule": row.AutoCreateDeliveryRule,
|
||||
"card_group_id": row.CardGroupID, "delivery_count": row.DeliveryCount,
|
||||
"status": row.Status, "item_id": row.ItemID, "item_url": row.ItemURL,
|
||||
"automation": automationCfg,
|
||||
"status": row.Status, "item_id": row.ItemID, "item_url": row.ItemURL,
|
||||
"error_message": row.ErrorMessage,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseMoneyCents(t *testing.T) {
|
||||
cases := map[string]int64{"1": 100, "1.2": 120, "¥12.34": 1234, "¥0.01": 1, "": 0}
|
||||
for raw, want := range cases {
|
||||
got, err := parseMoneyCents(raw)
|
||||
if err != nil || got != want {
|
||||
t.Errorf("parseMoneyCents(%q) = %d, %v; want %d", raw, got, err, want)
|
||||
}
|
||||
}
|
||||
if _, err := parseMoneyCents("1.2.3"); err == nil {
|
||||
t.Fatal("invalid money should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderImportParsers(t *testing.T) {
|
||||
csvData := []byte("订单号,商品ID,买家ID,金额,状态\no1,i1,b1,12.50,已付款\n")
|
||||
rows, err := parseImportedOrderBytes(csvData, "orders.csv")
|
||||
if err != nil || len(rows) != 1 {
|
||||
t.Fatalf("parse csv = %#v, %v", rows, err)
|
||||
}
|
||||
if rows[0]["order_id"] != "o1" || rows[0]["item_id"] != "i1" {
|
||||
t.Fatalf("normalized row = %#v", rows[0])
|
||||
}
|
||||
rows, err = parseImportedOrderBytes([]byte(`[{"order_id":"o2","amount":"9.9"}]`), "orders.json")
|
||||
if err != nil || len(rows) != 1 || rows[0]["order_id"] != "o2" {
|
||||
t.Fatalf("parse json = %#v, %v", rows, err)
|
||||
}
|
||||
if _, err := parseImportedOrderBytes(nil, "orders.csv"); err == nil {
|
||||
t.Fatal("empty import should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishBatchPathAndZipSafety(t *testing.T) {
|
||||
for _, raw := range []string{"../secret.png", "/etc/passwd", `..\\secret.png`, ""} {
|
||||
if _, err := safeZipPath(raw); err == nil {
|
||||
t.Errorf("safeZipPath(%q) should fail", raw)
|
||||
}
|
||||
}
|
||||
if got, err := safeZipPath("images/a.png"); err != nil || got != filepath.Join("images", "a.png") {
|
||||
t.Fatalf("safe path = %q, %v", got, err)
|
||||
}
|
||||
|
||||
dest := t.TempDir()
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
f, _ := zw.Create("images/a.png")
|
||||
_, _ = f.Write([]byte("not-an-image"))
|
||||
_ = zw.Close()
|
||||
if err := extractPublishImagesZip(buf.Bytes(), dest); err != nil {
|
||||
t.Fatalf("extract non-image: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, "images", "a.png")); !os.IsNotExist(err) {
|
||||
t.Fatal("non-image must not be extracted")
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
zw = zip.NewWriter(&buf)
|
||||
f, _ = zw.Create("../escape.png")
|
||||
_, _ = f.Write([]byte("x"))
|
||||
_ = zw.Close()
|
||||
if err := extractPublishImagesZip(buf.Bytes(), dest); err == nil {
|
||||
t.Fatal("zip traversal should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishBatchHelpers(t *testing.T) {
|
||||
if got := splitImageRefs("a.png; b.png\nc.png"); len(got) != 3 {
|
||||
t.Fatalf("splitImageRefs = %#v", got)
|
||||
}
|
||||
for _, value := range []string{"1", "TRUE", "yes", "是", "启用"} {
|
||||
if !parseLooseBool(value) {
|
||||
t.Errorf("parseLooseBool(%q) = false", value)
|
||||
}
|
||||
}
|
||||
if got := atoiPublishDefault("2.9", 1); got != 2 {
|
||||
t.Fatalf("atoiPublishDefault = %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePublishCardActions(t *testing.T) {
|
||||
actions, parseErr := parsePublishCardActions("101:1:0; 102:2:3")
|
||||
if parseErr != "" {
|
||||
t.Fatalf("parsePublishCardActions: %s", parseErr)
|
||||
}
|
||||
if len(actions) != 2 {
|
||||
t.Fatalf("actions=%+v", actions)
|
||||
}
|
||||
if actions[0].CardID != 101 || actions[0].DeliveryCount != 1 || actions[0].DelaySeconds != 0 {
|
||||
t.Fatalf("actions[0]=%+v", actions[0])
|
||||
}
|
||||
if actions[1].CardID != 102 || actions[1].DeliveryCount != 2 || actions[1].DelaySeconds != 3 {
|
||||
t.Fatalf("actions[1]=%+v", actions[1])
|
||||
}
|
||||
if _, parseErr := parsePublishCardActions("101:0"); parseErr == "" {
|
||||
t.Fatal("每件份数为0时应返回格式错误")
|
||||
}
|
||||
if got := normalizePublishHeader("付款后发送的卡密"); got != "paid_delivery_contents" {
|
||||
t.Fatalf("normalizePublishHeader=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePublishAutomationSupportsMultipleCards(t *testing.T) {
|
||||
cfg := parsePublishAutomation(map[string]any{
|
||||
"paid_delivery_enabled": "是",
|
||||
"paid_delivery_contents": "101:1:0;102:2:0",
|
||||
"review_gift_enabled": "true",
|
||||
"review_gift_contents": "201:1",
|
||||
})
|
||||
if !cfg.PaidDelivery.Enabled || len(cfg.PaidDelivery.Actions) != 2 {
|
||||
t.Fatalf("paid delivery=%+v", cfg.PaidDelivery)
|
||||
}
|
||||
if !cfg.ReviewGift.Enabled || len(cfg.ReviewGift.Actions) != 1 {
|
||||
t.Fatalf("review gift=%+v", cfg.ReviewGift)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicIPValidation(t *testing.T) {
|
||||
for _, raw := range []string{"127.0.0.1", "10.0.0.1", "169.254.1.1", "::1"} {
|
||||
if isPublicIP(net.ParseIP(raw)) {
|
||||
t.Errorf("private IP accepted: %s", raw)
|
||||
}
|
||||
}
|
||||
if !isPublicIP(net.ParseIP("8.8.8.8")) {
|
||||
t.Fatal("public IP rejected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestProtectedRouteGroupsRequireAuthentication(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
routes := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/cookies"},
|
||||
{http.MethodGet, "/api/orders"},
|
||||
{http.MethodGet, "/analytics/orders"},
|
||||
{http.MethodGet, "/cards"},
|
||||
{http.MethodGet, "/items"},
|
||||
{http.MethodGet, "/keywords/acc1"},
|
||||
{http.MethodGet, "/default-replies/acc1"},
|
||||
{http.MethodGet, "/notification-channels"},
|
||||
{http.MethodGet, "/system-settings"},
|
||||
{http.MethodGet, "/ai-reply-settings"},
|
||||
{http.MethodGet, "/user-settings"},
|
||||
{http.MethodGet, "/admin/stats"},
|
||||
}
|
||||
for _, route := range routes {
|
||||
t.Run(route.method+" "+route.path, func(t *testing.T) {
|
||||
req := httptest.NewRequest(route.method, route.path, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookiePreferenceEndpoints(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
requests := []struct {
|
||||
path string
|
||||
body string
|
||||
}{
|
||||
{"/cookies/acc1/auto-confirm", `{"auto_confirm":true}`},
|
||||
{"/cookies/acc1/remark", `{"remark":"primary"}`},
|
||||
{"/cookies/acc1/pause-duration", `{"pause_duration":30}`},
|
||||
}
|
||||
for _, tc := range requests {
|
||||
req := httptest.NewRequest(http.MethodPut, tc.path, strings.NewReader(tc.body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("PUT %s status=%d body=%s", tc.path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
for _, path := range []string{"/cookies/acc1/auto-confirm", "/cookies/acc1/pause-duration", "/cookie/acc1/details"} {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("GET %s status=%d body=%s", path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/pause-duration", strings.NewReader(`{"pause_duration":-1}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("negative pause status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,8 @@
|
||||
<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-DUZvff1P.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-DV2rPmKw.css">
|
||||
<script type="module" crossorigin src="/static/assets/index-WNdAs3ij.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-jAhq_csJ.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// Package webui 提供嵌入式前端构建产物。
|
||||
package webui
|
||||
|
||||
import (
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStaticContainsIndex(t *testing.T) {
|
||||
static, err := Static()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := fs.ReadFile(static, "index.html")
|
||||
if err != nil || len(data) == 0 {
|
||||
t.Fatalf("embedded index missing: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package mtop 实现闲鱼 mtop H5 API 客户端,移植自 Python 端 refresh_token()。
|
||||
// Package mtop 实现闲鱼 mtop H5 API 客户端。
|
||||
// 关键:签名只覆盖 (t, token, data_val),与 URL query 参数无关;token 取自 cookie _m_h5_tk 前半段。
|
||||
package mtop
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// WS 注册用的 appKey(注意与签名用的 protocol.SignAppKey=34839810 不同)。
|
||||
// RegAppKey 是 WS 注册用的 appKey(与签名用的 protocol.SignAppKey 不同)。
|
||||
const RegAppKey = "444e9908a51d1cb236a27862abc769c9"
|
||||
|
||||
// TokenAPI 取 access token 的端点。
|
||||
@@ -801,7 +801,7 @@ func (c *Client) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID stri
|
||||
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
dataVal := `{"appKey":"` + RegAppKey + `","deviceId":"` + deviceID + `"}`
|
||||
|
||||
// query 参数(值按 Python 端原样构造;签名不覆盖 query,故编码细节不影响验签)。
|
||||
// 签名不覆盖 query,因此 query 的编码细节不影响验签。
|
||||
query := buildTokenQuery(t, protocol.GenerateSign(t, token, dataVal))
|
||||
|
||||
body := "data=" + url.QueryEscape(dataVal)
|
||||
@@ -854,7 +854,7 @@ func (c *Client) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID stri
|
||||
return res.Data.AccessToken, res.Ret, updated, resp.StatusCode, nil
|
||||
}
|
||||
|
||||
// buildTokenQuery 构造 token API 的 query string,参数顺序与 Python 端一致。
|
||||
// buildTokenQuery 构造 token API 的 query string。
|
||||
// 值按原样拼接(dangerouslySetWindvaneParams 已是单次编码),不做二次编码。
|
||||
func buildTokenQuery(t, sign string) string {
|
||||
parts := [][2]string{
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPublishPayloadBuilders(t *testing.T) {
|
||||
req := PublishItemRequest{PriceCents: 1234, OriginalPriceCents: 2000, PostageMode: "fixed", PostageCents: 800}
|
||||
price := publishPriceDTO(req)
|
||||
if price["priceInCent"] != "1234" || price["origPriceInCent"] != "2000" {
|
||||
t.Fatalf("publishPriceDTO = %#v", price)
|
||||
}
|
||||
postage := postageDTO(req)
|
||||
if postage["postPriceInCent"] != "800" || postage["templateId"] != "0" {
|
||||
t.Fatalf("postageDTO = %#v", postage)
|
||||
}
|
||||
if got := postageDTO(PublishItemRequest{PostageMode: "free"}); got["canFreeShipping"] != true {
|
||||
t.Fatalf("free postage = %#v", got)
|
||||
}
|
||||
if got := postageDTO(PublishItemRequest{PostageMode: "distance"}); got["templateId"] != "-100" {
|
||||
t.Fatalf("distance postage = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishParsingAndErrors(t *testing.T) {
|
||||
if w, h := parsePix("800x600"); w != 800 || h != 600 {
|
||||
t.Fatalf("parsePix = %d x %d", w, h)
|
||||
}
|
||||
if w, h := parsePix("bad"); w != 0 || h != 0 {
|
||||
t.Fatalf("invalid parsePix = %d x %d", w, h)
|
||||
}
|
||||
if got := centsText(1234); got != "12.34" {
|
||||
t.Fatalf("centsText = %q", got)
|
||||
}
|
||||
if got := findStringDeep(map[string]any{"outer": map[string]any{"itemId": "42"}}, "itemId"); got != "42" {
|
||||
t.Fatalf("findStringDeep = %q", got)
|
||||
}
|
||||
|
||||
err := classifyPublishError([]string{"FAIL_SYS_TOKEN_EXPIRED::令牌过期"}, map[string]any{})
|
||||
var publishErr *PublishError
|
||||
if !errors.As(err, &publishErr) || publishErr.Code != PublishErrorTokenExpired {
|
||||
t.Fatalf("token error = %#v", err)
|
||||
}
|
||||
err = classifyPublishError([]string{"账号没有库存发布权限"}, map[string]any{})
|
||||
if !errors.As(err, &publishErr) || publishErr.Code != PublishErrorStockPermissionMissing {
|
||||
t.Fatalf("stock error = %#v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,9 @@
|
||||
// Package protocol 移植自 Python 端 utils/xianyu_utils.py 的协议原语:
|
||||
// cookie 解析、mtop 签名、设备/消息 ID 生成、消息解密(base64 + MessagePack)。
|
||||
//
|
||||
// 这些算法与 Python 实现逐字节对齐,并通过 golden 测试(用真实抓包样本对比)锁定。
|
||||
// Package protocol 提供 cookie 解析、mtop 签名、设备/消息 ID 生成和消息解密。
|
||||
package protocol
|
||||
|
||||
import "strings"
|
||||
|
||||
// TransCookies 将 "k1=v1; k2=v2" 形式的 cookie 字符串解析为 map。
|
||||
// 对应 Python trans_cookies(cookies_str)。
|
||||
func TransCookies(cookiesStr string) map[string]string {
|
||||
cookies := make(map[string]string)
|
||||
if cookiesStr == "" {
|
||||
|
||||
@@ -9,12 +9,11 @@ import (
|
||||
)
|
||||
|
||||
// Decrypt 解密闲鱼 WS 同步包载荷:base64 解码 → MessagePack 解码 → 归一化为 JSON 字符串。
|
||||
// 对应 Python decrypt(data)。归一化规则与 Python json.dumps(default=bytes→utf-8) 一致:
|
||||
// - map 的键统一转为字符串(整数键 → 数字字符串,与 Python json 行为一致)
|
||||
// - map 的键统一转为字符串(整数键 → 数字字符串)
|
||||
// - []byte(msgpack bin)→ UTF-8 字符串(忽略无效字节)
|
||||
// - 其余类型原样保留
|
||||
func Decrypt(data string) (string, error) {
|
||||
// 清理非 ASCII(与 Python 一致:utf-8 编码后按 ascii 忽略解码)。
|
||||
// 清理非 ASCII。
|
||||
data = stripNonASCII(data)
|
||||
|
||||
// base64 解码,必要时补 padding。
|
||||
@@ -42,7 +41,7 @@ func Decrypt(data string) (string, error) {
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// stripNonASCII 模拟 Python data.encode('utf-8','ignore').decode('ascii','ignore')。
|
||||
// stripNonASCII 删除非 ASCII 字符。
|
||||
func stripNonASCII(s string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
@@ -54,8 +53,7 @@ func stripNonASCII(s string) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// normalizeForJSON 把 msgpack 解码出的任意结构转为 json.Marshal 友好的结构,
|
||||
// 并复刻 Python json.dumps 的键/字节处理。
|
||||
// normalizeForJSON 把 msgpack 解码出的任意结构转为 json.Marshal 友好的结构。
|
||||
func normalizeForJSON(v any) any {
|
||||
switch x := v.(type) {
|
||||
case map[any]any:
|
||||
@@ -71,14 +69,14 @@ func normalizeForJSON(v any) any {
|
||||
}
|
||||
return out
|
||||
case []byte:
|
||||
// Python default 序列化器:bytes.decode('utf-8','ignore')
|
||||
// 忽略无效 UTF-8 字节。
|
||||
return strings.ToValidUTF8(string(x), "")
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// keyToString 复刻 Python json 对非字符串键的转换。
|
||||
// keyToString 将非字符串 map 键转换为 JSON 对象键。
|
||||
func keyToString(k any) string {
|
||||
switch x := k.(type) {
|
||||
case string:
|
||||
|
||||
@@ -14,7 +14,7 @@ var sampleB64 string
|
||||
//go:embed testdata/expected_decrypt.json
|
||||
var expectedDecrypt string
|
||||
|
||||
// TestGenerateSign_Golden 与 Python hashlib.md5 结果逐字节对比。
|
||||
// TestGenerateSign_Golden 锁定签名结果。
|
||||
func TestGenerateSign_Golden(t *testing.T) {
|
||||
got := GenerateSign("1700000000000", "abc_token", `{"appKey":"x"}`)
|
||||
want := "497ff18ef9c6d4792ba5aeef0e99929a"
|
||||
@@ -23,7 +23,7 @@ func TestGenerateSign_Golden(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDecrypt_Golden 用真实抓包样本对比 Python decrypt 的输出。
|
||||
// TestDecrypt_Golden 用真实抓包样本锁定解密输出。
|
||||
// 比较方式:两侧都按 JSON 解析(UseNumber 保留整数精度),reflect.DeepEqual 结构相等。
|
||||
func TestDecrypt_Golden(t *testing.T) {
|
||||
got, err := Decrypt(strings.TrimSpace(sampleB64))
|
||||
@@ -39,6 +39,42 @@ func TestDecrypt_Golden(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagePackSignedIntegers(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw []byte
|
||||
want int64
|
||||
}{
|
||||
{"negative fixint", []byte{0xff}, -1},
|
||||
{"int8", []byte{0xd0, 0x80}, -128},
|
||||
{"int16", []byte{0xd1, 0xff, 0xfe}, -2},
|
||||
{"int32", []byte{0xd2, 0xff, 0xff, 0xff, 0xfd}, -3},
|
||||
{"int64", []byte{0xd3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}, -4},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
decoder := &msgpackDecoder{data: tc.raw}
|
||||
got, err := decoder.decodeValue()
|
||||
if err != nil || got != tc.want {
|
||||
t.Fatalf("decodeValue() = %#v, %v; want %d", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneratedIdentifiers(t *testing.T) {
|
||||
if mid := GenerateMid(); !strings.HasSuffix(mid, " 0") {
|
||||
t.Fatalf("invalid mid: %q", mid)
|
||||
}
|
||||
if uuid := GenerateUUID(); !strings.HasPrefix(uuid, "-") || !strings.HasSuffix(uuid, "1") {
|
||||
t.Fatalf("invalid uuid: %q", uuid)
|
||||
}
|
||||
deviceID := GenerateDeviceID("123")
|
||||
if len(deviceID) != 40 || !strings.HasSuffix(deviceID, "-123") || deviceID[14] != '4' {
|
||||
t.Fatalf("invalid device ID: %q", deviceID)
|
||||
}
|
||||
}
|
||||
|
||||
func mustParseJSONUseNumber(t *testing.T, s string) any {
|
||||
t.Helper()
|
||||
dec := json.NewDecoder(strings.NewReader(s))
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"math"
|
||||
)
|
||||
|
||||
// msgpackDecoder 是 Python MessagePackDecoder 的逐格式移植。
|
||||
// msgpackDecoder 解析闲鱼消息使用的 MessagePack 数据。
|
||||
// 解码结果类型:int64/uint64/float64/string/bool/nil/[]byte/[]any/map[any]any。
|
||||
// 与 Python 实现一致:bin → []byte,map 键保留原类型(整数键为 int64)。
|
||||
// bin 解码为 []byte,map 键保留原类型(整数键为 int64)。
|
||||
type msgpackDecoder struct {
|
||||
data []byte
|
||||
pos int
|
||||
@@ -112,25 +112,26 @@ func (d *msgpackDecoder) decodeValue() (any, error) {
|
||||
return binary.BigEndian.Uint64(b), nil
|
||||
case 0xd0: // int 8
|
||||
n, err := d.readByte()
|
||||
// #nosec G115 -- MessagePack 有符号整数使用二进制补码编码,此转换用于符号扩展。
|
||||
return int64(int8(n)), err
|
||||
case 0xd1: // int 16
|
||||
b, err := d.readBytes(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return int64(int16(binary.BigEndian.Uint16(b))), nil
|
||||
return int64(int16(binary.BigEndian.Uint16(b))), nil // #nosec G115 -- 协议要求的符号扩展
|
||||
case 0xd2: // int 32
|
||||
b, err := d.readBytes(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return int64(int32(binary.BigEndian.Uint32(b))), nil
|
||||
return int64(int32(binary.BigEndian.Uint32(b))), nil // #nosec G115 -- 协议要求的符号扩展
|
||||
case 0xd3: // int 64
|
||||
b, err := d.readBytes(8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return int64(binary.BigEndian.Uint64(b)), nil
|
||||
return int64(binary.BigEndian.Uint64(b)), nil // #nosec G115 -- 协议要求的符号扩展
|
||||
case 0xd9: // str 8
|
||||
n, err := d.readByte()
|
||||
if err != nil {
|
||||
@@ -176,6 +177,7 @@ func (d *msgpackDecoder) decodeValue() (any, error) {
|
||||
}
|
||||
// negative fixint
|
||||
if fb >= 0xe0 {
|
||||
// #nosec G115 -- negative fixint 使用二进制补码编码。
|
||||
return int64(int8(fb)), nil
|
||||
}
|
||||
return nil, fmt.Errorf("msgpack: unknown format byte 0x%02x", fb)
|
||||
@@ -186,7 +188,7 @@ func (d *msgpackDecoder) readString(n int) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(b), nil // UTF-8,与 Python .decode('utf-8') 一致
|
||||
return string(b), nil // UTF-8
|
||||
}
|
||||
|
||||
func (d *msgpackDecoder) decodeArray(n int) (any, error) {
|
||||
|
||||
@@ -2,33 +2,33 @@ package protocol
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"math/big"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// mtop 签名使用的 appKey(与 WS 注册用的 APP_CONFIG.app_key 不同)。
|
||||
// SignAppKey 是 mtop 签名使用的 appKey(与 WS 注册用的 appKey 不同)。
|
||||
const SignAppKey = "34839810"
|
||||
|
||||
// GenerateSign 生成 mtop API 签名:MD5(token + "&" + t + "&" + appKey + "&" + data)。
|
||||
// 对应 Python generate_sign(t, token, data)。
|
||||
func GenerateSign(t, token, data string) string {
|
||||
msg := token + "&" + t + "&" + SignAppKey + "&" + data
|
||||
// #nosec G401 -- MTOP 协议明确要求 MD5,不能替换为其他摘要算法。
|
||||
sum := md5.Sum([]byte(msg))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// GenerateMid 生成消息 ID,形如 "<0-999随机><毫秒时间戳> 0"。
|
||||
// 对应 Python generate_mid()。非密码学用途,用 math/rand 即可。
|
||||
// GenerateMid 生成非密码学用途的消息 ID,形如 "<0-999随机><毫秒时间戳> 0"。
|
||||
func GenerateMid() string {
|
||||
randomPart := rand.Intn(1000)
|
||||
randomPart := randomInt(1000)
|
||||
ts := time.Now().UnixMilli()
|
||||
return fmt.Sprintf("%d%d 0", randomPart, ts)
|
||||
}
|
||||
|
||||
// GenerateUUID 生成 UUID,形如 "-<毫秒时间戳>1"。
|
||||
// 对应 Python generate_uuid()。
|
||||
func GenerateUUID() string {
|
||||
return fmt.Sprintf("-%d1", time.Now().UnixMilli())
|
||||
}
|
||||
@@ -37,7 +37,6 @@ const deviceIDChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstu
|
||||
|
||||
// GenerateDeviceID 生成设备 ID:36 位 UUID 格式(位置 8/13/18/23 为 "-",14 为 "4",
|
||||
// 19 取 (rand&0x3)|0x8),末尾追加 "-<userID>"。
|
||||
// 对应 Python generate_device_id(user_id)。
|
||||
func GenerateDeviceID(userID string) string {
|
||||
result := make([]byte, 36)
|
||||
for i := 0; i < 36; i++ {
|
||||
@@ -47,10 +46,24 @@ func GenerateDeviceID(userID string) string {
|
||||
case i == 14:
|
||||
result[i] = '4'
|
||||
case i == 19:
|
||||
result[i] = deviceIDChars[(rand.Intn(16)&0x3)|0x8]
|
||||
result[i] = deviceIDChars[(randomInt(16)&0x3)|0x8]
|
||||
default:
|
||||
result[i] = deviceIDChars[rand.Intn(16)]
|
||||
result[i] = deviceIDChars[randomInt(16)]
|
||||
}
|
||||
}
|
||||
return string(result) + "-" + userID
|
||||
}
|
||||
|
||||
var randomFallback atomic.Uint64
|
||||
|
||||
// randomInt 返回 [0,max) 的密码学随机数;系统熵源异常时使用进程内单调计数兜底。
|
||||
func randomInt(max int) int {
|
||||
if max <= 1 {
|
||||
return 0
|
||||
}
|
||||
n, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
|
||||
if err == nil {
|
||||
return int(n.Int64())
|
||||
}
|
||||
return int(randomFallback.Add(1) % uint64(max))
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
// Package qrlogin 实现闲鱼扫码登录;风控验证场景可通过浏览器提取真实 cookie。
|
||||
// 移植自 Python utils/qr_login.py 的 QRLoginManager。
|
||||
package qrlogin
|
||||
|
||||
import (
|
||||
@@ -69,10 +68,10 @@ func (s *Session) isExpired() bool {
|
||||
return time.Since(s.createdTime) > s.expireTime
|
||||
}
|
||||
|
||||
// SidecarRefresher 由外部注入的浏览器刷新函数。
|
||||
// BrowserRefresher 由外部注入的浏览器刷新函数。
|
||||
// tmpCookies: 扫码临时 cookie;verificationURL: Chromium 打开后持有 session 等待验证。
|
||||
// onScreenshot: 每次截图时回调(data:image/png;base64,...),前端实时显示验证页画面。
|
||||
type SidecarRefresher func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (realCookies string, unb string, err error)
|
||||
type BrowserRefresher func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (realCookies string, unb string, err error)
|
||||
|
||||
// Manager 扫码登录管理器。
|
||||
type Manager struct {
|
||||
@@ -80,12 +79,12 @@ type Manager struct {
|
||||
sessions map[string]*Session
|
||||
httpc *http.Client
|
||||
logger *slog.Logger
|
||||
sidecar SidecarRefresher // 可选:风控验证后用浏览器提取真实 cookie
|
||||
browser BrowserRefresher // 可选:风控验证后用浏览器提取真实 cookie
|
||||
}
|
||||
|
||||
// SetSidecarRefresher 注入 sidecar 刷新函数(风控验证场景必需)。
|
||||
func (m *Manager) SetSidecarRefresher(f SidecarRefresher) {
|
||||
m.sidecar = f
|
||||
// SetBrowserRefresher 注入浏览器刷新函数(风控验证场景必需)。
|
||||
func (m *Manager) SetBrowserRefresher(f BrowserRefresher) {
|
||||
m.browser = f
|
||||
}
|
||||
|
||||
// NewManager 构造。
|
||||
@@ -102,7 +101,10 @@ func NewManager(logger *slog.Logger) *Manager {
|
||||
|
||||
// GenerateQRCode 生成扫码登录二维码。返回 session_id + qr_code_url(base64 data URL)。
|
||||
func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeURL string, err error) {
|
||||
sessionID = randomUUID()
|
||||
sessionID, err = randomUUID()
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("生成扫码会话 ID: %w", err)
|
||||
}
|
||||
sess := &Session{
|
||||
SessionID: sessionID,
|
||||
Status: "waiting",
|
||||
@@ -186,8 +188,13 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
|
||||
m.sessions[sessionID] = sess
|
||||
m.mu.Unlock()
|
||||
|
||||
// 5. 后台轮询扫码状态。
|
||||
go m.monitorQRStatus(context.Background(), sessionID)
|
||||
// 5. 扫码会话独立于生成二维码的 HTTP 请求,但受会话有效期约束。
|
||||
// #nosec G118 -- 后台任务必须跨越原请求,且由超时上下文保证退出。
|
||||
go func() {
|
||||
monitorCtx, cancel := context.WithTimeout(context.Background(), sess.expireTime)
|
||||
defer cancel()
|
||||
m.monitorQRStatus(monitorCtx, sessionID)
|
||||
}()
|
||||
|
||||
m.logger.Info("二维码生成成功", "session_id", sessionID)
|
||||
return sessionID, qrCodeURL, nil
|
||||
@@ -222,19 +229,7 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
|
||||
return result
|
||||
}
|
||||
|
||||
// CleanupExpired 清理过期会话。
|
||||
func (m *Manager) CleanupExpired() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for id, s := range m.sessions {
|
||||
if s.isExpired() && s.Status != "success" {
|
||||
delete(m.sessions, id)
|
||||
m.logger.Info("清理过期扫码会话", "session_id", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// monitorQRStatus 后台轮询扫码状态(移植自 Python _monitor_qr_status)。
|
||||
// monitorQRStatus 后台轮询扫码状态。
|
||||
func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
m.mu.Lock()
|
||||
sess := m.sessions[sessionID]
|
||||
@@ -266,8 +261,12 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
||||
closeErr := resp.Body.Close()
|
||||
if readErr != nil || closeErr != nil {
|
||||
m.logger.Warn("读取扫码状态响应失败", "read_err", readErr, "close_err", closeErr)
|
||||
continue
|
||||
}
|
||||
|
||||
var qrResult struct {
|
||||
Content struct {
|
||||
@@ -278,7 +277,10 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
} `json:"data"`
|
||||
} `json:"content"`
|
||||
}
|
||||
json.Unmarshal(body, &qrResult)
|
||||
if err := json.Unmarshal(body, &qrResult); err != nil {
|
||||
m.logger.Warn("解析扫码状态响应失败", "err", err)
|
||||
continue
|
||||
}
|
||||
|
||||
status := qrResult.Content.Data.QRCodeStatus
|
||||
switch status {
|
||||
@@ -298,11 +300,14 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
// 用户在手机完成验证后,服务端回调打到这个 Chromium 页面(redirect 到 ivCheckLogin.htm),
|
||||
// Chromium 才能拿到授权 session,再访问 /im 得到 unb。
|
||||
// 不能等用户点按钮——那时验证已绑定到用户浏览器 session,与此 Chromium 无关。
|
||||
if m.sidecar != nil {
|
||||
sidecarFn := m.sidecar
|
||||
if m.browser != nil {
|
||||
browserFn := m.browser
|
||||
cookieStr := cookieMarshal(sess.cookies)
|
||||
verURL := sess.verificationURL
|
||||
// #nosec G118 -- 浏览器验证必须跨越轮询请求,浏览器实现本身有超时限制。
|
||||
go func() {
|
||||
verifyCtx, cancel := context.WithTimeout(context.Background(), sess.expireTime)
|
||||
defer cancel()
|
||||
onScreenshot := func(dataURL string) {
|
||||
m.mu.Lock()
|
||||
if s, ok := m.sessions[sessionID]; ok {
|
||||
@@ -310,7 +315,7 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
realCookies, unb, err := sidecarFn(context.Background(), cookieStr, verURL, onScreenshot)
|
||||
realCookies, unb, err := browserFn(verifyCtx, cookieStr, verURL, onScreenshot)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s, ok := m.sessions[sessionID]
|
||||
@@ -374,7 +379,6 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
|
||||
// CompleteVerification 用户完成风控验证后调用:先用扫码临时 cookie 访问 goofish.com/im,
|
||||
// 必要时再使用浏览器提取真实 cookie(含 unb)。
|
||||
// 移植自 Python refresh_cookies_from_qr_login 的核心,并保留浏览器兜底。
|
||||
func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error) {
|
||||
m.mu.Lock()
|
||||
sess, ok := m.sessions[sessionID]
|
||||
@@ -399,13 +403,15 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
|
||||
|
||||
resp, err := jarClient.Do(req)
|
||||
if err != nil {
|
||||
if m.sidecar == nil {
|
||||
if m.browser == nil {
|
||||
return "", "", fmt.Errorf("访问 goofish.com/im 失败: %w", err)
|
||||
}
|
||||
m.logger.Warn("纯 HTTP 访问 goofish.com/im 失败,改用 sidecar 提取", "session_id", sessionID, "err", err)
|
||||
m.logger.Warn("纯 HTTP 访问 goofish.com/im 失败,改用浏览器提取", "session_id", sessionID, "err", err)
|
||||
} else {
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return "", "", fmt.Errorf("读取验证响应失败: %w", err)
|
||||
}
|
||||
|
||||
// 收集 Set-Cookie。
|
||||
for _, c := range resp.Cookies() {
|
||||
@@ -416,9 +422,9 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
|
||||
}
|
||||
}
|
||||
|
||||
// 如果还没 unb 且没有 sidecar,再访问 mtop token API 触发(有时需要额外请求)。
|
||||
// 有 sidecar 时直接走浏览器路径,避免在风控场景中重复纯 HTTP 请求。
|
||||
if sess.unb == "" && m.sidecar == nil {
|
||||
// 如果还没 unb 且没有浏览器刷新器,再访问 mtop token API 触发(有时需要额外请求)。
|
||||
// 有浏览器刷新器时直接走浏览器路径,避免在风控场景中重复纯 HTTP 请求。
|
||||
if sess.unb == "" && m.browser == nil {
|
||||
m.logger.Info("首次访问未拿到 unb,尝试 mtop token API", "session_id", sessionID)
|
||||
if err := m.getMH5TK(ctx, sess); err != nil {
|
||||
m.logger.Warn("mtop token API 失败", "err", err)
|
||||
@@ -433,30 +439,30 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
|
||||
}
|
||||
|
||||
// 纯 HTTP 拿不到 unb(闲鱼真实 cookie 由页面 JS 异步下发),
|
||||
// 风控验证后的 cookie 提取必须依赖 sidecar(playwright 浏览器)。
|
||||
if m.sidecar == nil {
|
||||
// 风控验证后的 cookie 提取必须依赖浏览器。
|
||||
if m.browser == nil {
|
||||
return "", "", fmt.Errorf("风控验证后的 cookie 提取需要浏览器支持(请勿使用 -no-browser 启动)")
|
||||
}
|
||||
|
||||
m.logger.Info("纯 HTTP 未拿到 unb,调用 sidecar 浏览器提取", "session_id", sessionID)
|
||||
realCookies, sidecarUNB, err := m.sidecar(ctx, cookieMarshal(sess.cookies), sess.verificationURL, nil)
|
||||
m.logger.Info("纯 HTTP 未拿到 unb,调用浏览器提取", "session_id", sessionID)
|
||||
realCookies, browserUNB, err := m.browser(ctx, cookieMarshal(sess.cookies), sess.verificationURL, nil)
|
||||
if err != nil {
|
||||
m.logger.Error("sidecar 提取失败", "err", err)
|
||||
m.logger.Error("浏览器提取失败", "err", err)
|
||||
return "", "", fmt.Errorf("浏览器提取 cookie 失败: %w", err)
|
||||
}
|
||||
parsedCookies := parseCookieStr(realCookies)
|
||||
if len(parsedCookies) == 0 {
|
||||
return "", "", fmt.Errorf("浏览器提取 cookie 失败: sidecar 未返回有效 cookie")
|
||||
return "", "", fmt.Errorf("浏览器提取 cookie 失败: 未返回有效 cookie")
|
||||
}
|
||||
sess.cookies = parsedCookies
|
||||
sess.unb = sidecarUNB
|
||||
sess.unb = browserUNB
|
||||
if sess.unb == "" {
|
||||
sess.unb = sess.cookies["unb"]
|
||||
}
|
||||
if sess.unb == "" {
|
||||
return "", "", fmt.Errorf("验证后仍未获取到 unb,可能验证未完成或临时 cookie 已失效")
|
||||
}
|
||||
m.logger.Info("sidecar 提取成功", "session_id", sessionID, "account_hash", logsafe.ID(sess.unb), "cookie_count", len(sess.cookies))
|
||||
m.logger.Info("浏览器提取成功", "session_id", sessionID, "account_hash", logsafe.ID(sess.unb), "cookie_count", len(sess.cookies))
|
||||
|
||||
sess.Status = "success"
|
||||
return cookieMarshal(sess.cookies), sess.unb, nil
|
||||
@@ -473,7 +479,7 @@ func parseCookieStr(s string) map[string]string {
|
||||
return m
|
||||
}
|
||||
|
||||
// getMH5TK 获取 m_h5_tk(移植自 Python _get_mh5tk)。
|
||||
// getMH5TK 获取 m_h5_tk。
|
||||
func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiH5TK, nil)
|
||||
m.setHeaders(req)
|
||||
@@ -483,7 +489,9 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 合并 Set-Cookie。
|
||||
for _, c := range resp.Cookies() {
|
||||
@@ -522,7 +530,9 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
return err
|
||||
}
|
||||
defer resp2.Body.Close()
|
||||
io.Copy(io.Discard, resp2.Body)
|
||||
if _, err := io.Copy(io.Discard, resp2.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 更新 cookie。
|
||||
for _, c := range resp2.Cookies() {
|
||||
@@ -531,7 +541,7 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// getLoginParams 获取登录表单参数(移植自 Python _get_login_params)。
|
||||
// getLoginParams 获取登录表单参数。
|
||||
func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string]string, error) {
|
||||
params := url.Values{}
|
||||
params.Set("lang", "zh_cn")
|
||||
@@ -617,6 +627,7 @@ func (m *Manager) setHeaders(req *http.Request) {
|
||||
// ---- 工具函数 ----
|
||||
|
||||
func md5hex(s string) string {
|
||||
// #nosec G401 -- 闲鱼登录协议明确要求 MD5,不能替换为其他摘要算法。
|
||||
h := md5.Sum([]byte(s))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
@@ -629,18 +640,15 @@ func cookieMarshal(cookies map[string]string) string {
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
func randomUUID() string {
|
||||
func randomUUID() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(randReader, b); err != nil {
|
||||
// 降级到时间种子(极少见)
|
||||
for i := range b {
|
||||
b[i] = byte(time.Now().UnixNano() >> (i * 8))
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
|
||||
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||
}
|
||||
|
||||
var randReader io.Reader = rand.Reader
|
||||
|
||||
@@ -2,6 +2,8 @@ package qrlogin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -9,7 +11,11 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCompleteVerificationRequiresSidecarWhenHTTPMissingUNB(t *testing.T) {
|
||||
type failingReader struct{}
|
||||
|
||||
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("entropy unavailable") }
|
||||
|
||||
func TestCompleteVerificationRequiresBrowserWhenHTTPMissingUNB(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s1"] = testVerificationSession()
|
||||
oldTarget := qrVerifyTargetURL
|
||||
@@ -22,12 +28,12 @@ func TestCompleteVerificationRequiresSidecarWhenHTTPMissingUNB(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationSidecarSuccess(t *testing.T) {
|
||||
func TestCompleteVerificationBrowserSuccess(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s1"] = testVerificationSession()
|
||||
m.SetSidecarRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
if !strings.Contains(tmpCookies, "tmp=1") {
|
||||
t.Fatalf("sidecar 收到临时 cookie 异常: %q", tmpCookies)
|
||||
t.Fatalf("浏览器刷新器收到临时 cookie 异常: %q", tmpCookies)
|
||||
}
|
||||
return "unb=999; cookie2=abc", "999", nil
|
||||
})
|
||||
@@ -47,10 +53,10 @@ func TestCompleteVerificationSidecarSuccess(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationSidecarUNBFromCookieMap(t *testing.T) {
|
||||
func TestCompleteVerificationBrowserUNBFromCookieMap(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s1"] = testVerificationSession()
|
||||
m.SetSidecarRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
return "unb=888; cookie2=abc", "", nil
|
||||
})
|
||||
oldTarget := qrVerifyTargetURL
|
||||
@@ -74,6 +80,20 @@ func TestCompleteVerificationMissingSession(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomUUIDRequiresEntropy(t *testing.T) {
|
||||
original := randReader
|
||||
t.Cleanup(func() { randReader = original })
|
||||
randReader = failingReader{}
|
||||
if _, err := randomUUID(); err == nil {
|
||||
t.Fatal("randomUUID should fail when entropy source fails")
|
||||
}
|
||||
randReader = io.LimitReader(strings.NewReader("0123456789abcdef"), 16)
|
||||
id, err := randomUUID()
|
||||
if err != nil || len(id) != 36 || id[14] != '4' {
|
||||
t.Fatalf("randomUUID() = %q, %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func testVerificationSession() *Session {
|
||||
return &Session{
|
||||
SessionID: "s1",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// 否则版本号自相矛盾会被风控识别为伪造。这里集中定义,三处引用同一常量,杜绝不一致。
|
||||
//
|
||||
// 版本号选择原则:用主流稳定版区间,避免太新(显得伪造)或太旧(显得异常)。
|
||||
// Chrome/138 是 Python 原项目实测可跑通的版本之一。
|
||||
// 浏览器版本必须与实际安装的 Chromium 保持一致。
|
||||
package xianyu
|
||||
|
||||
// ChromeVer 统一的 Chrome 版本号,所有 UA 引用此常量。
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// Package ws 实现闲鱼 WebSocket 连接生命周期:握手、/reg 注册、心跳、ACK、消息解密。
|
||||
// 移植自 Python XianyuAutoAsync.py 的 main/init/send_heartbeat/handle_message。
|
||||
package ws
|
||||
|
||||
import (
|
||||
@@ -76,7 +75,7 @@ func Dial(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
|
||||
|
||||
conn := &Conn{ws: c, cfg: cfg, logger: logger, recorder: cfg.Recorder}
|
||||
if err := conn.register(ctx); err != nil {
|
||||
c.CloseNow()
|
||||
_ = c.CloseNow()
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
@@ -102,7 +101,7 @@ func (c *Conn) register(ctx context.Context) error {
|
||||
return fmt.Errorf("发送 /reg 失败: %w", err)
|
||||
}
|
||||
|
||||
// Python 端在 /reg 后 sleep 1s 再发 ackDiff,这里用 1s 等待。
|
||||
// /reg 后等待 1 秒再发送 ackDiff。
|
||||
select {
|
||||
case <-time.After(time.Second):
|
||||
case <-ctx.Done():
|
||||
@@ -196,7 +195,7 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
|
||||
c.logger.Debug("收到响应", "code", code)
|
||||
}
|
||||
|
||||
// 先回 ACK(与 Python handle_message 一致)。
|
||||
// 收到消息后先回复 ACK。
|
||||
c.sendACK(ctx, raw)
|
||||
|
||||
// 仅处理同步包:body.syncPushPackage.data[0].data
|
||||
@@ -226,7 +225,7 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
|
||||
}
|
||||
}
|
||||
|
||||
// sendACK 回复 {"code":200, headers:{mid,sid,...}},失败静默(与 Python except: pass 一致)。
|
||||
// sendACK 回复 {"code":200, headers:{mid,sid,...}},失败时仅记录日志。
|
||||
func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
|
||||
headers, _ := msg["headers"].(map[string]any)
|
||||
ack := map[string]any{
|
||||
@@ -280,7 +279,7 @@ func extractSyncPayload(msg map[string]any) (string, bool) {
|
||||
|
||||
// decodeSyncData 先尝试 base64+JSON(未加密系统消息),失败则 base64+msgpack 解密。
|
||||
func decodeSyncData(data string) (map[string]any, error) {
|
||||
// 1) 先按 Python:base64 解码 → 尝试 JSON
|
||||
// 1) base64 解码后尝试解析 JSON。
|
||||
if dec, err := base64.StdEncoding.DecodeString(data); err == nil {
|
||||
var parsed map[string]any
|
||||
if jsonErr := json.Unmarshal(dec, &parsed); jsonErr == nil {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtractSyncPayload(t *testing.T) {
|
||||
msg := map[string]any{"body": map[string]any{"syncPushPackage": map[string]any{
|
||||
"data": []any{map[string]any{"data": "payload"}},
|
||||
}}}
|
||||
if got, ok := extractSyncPayload(msg); !ok || got != "payload" {
|
||||
t.Fatalf("extractSyncPayload() = %q, %v", got, ok)
|
||||
}
|
||||
for _, invalid := range []map[string]any{{}, {"body": map[string]any{}}, {"body": map[string]any{"syncPushPackage": map[string]any{"data": []any{}}}}} {
|
||||
if _, ok := extractSyncPayload(invalid); ok {
|
||||
t.Fatalf("invalid payload accepted: %#v", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeSyncDataJSONAndInvalid(t *testing.T) {
|
||||
raw := base64.StdEncoding.EncodeToString([]byte(`{"event":"paid","count":2}`))
|
||||
got, err := decodeSyncData(raw)
|
||||
if err != nil || got["event"] != "paid" || got["count"] != float64(2) {
|
||||
t.Fatalf("decodeSyncData() = %#v, %v", got, err)
|
||||
}
|
||||
if _, err := decodeSyncData("not-base64"); err == nil {
|
||||
t.Fatal("invalid payload should fail")
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user