feat(发布与自动化): 完善批量发布分类兜底和规则管理
This commit is contained in:
1 parent
fd30a0d17a
commit
b98c4edf68
31 files changed
+1032
-130
No files matched your search
@@ -47,7 +47,7 @@ Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名
|
||||
- 多个闲鱼账号的统一在线状态与消息管理
|
||||
- 数字商品、兑换码、链接或图片内容的自动交付
|
||||
- 付款后发货、评价赠品、超时求评价等自动化流程
|
||||
- 商品与订单同步、单商品发布及表格批量铺货
|
||||
- 商品与订单同步、单商品发布及带逐行/批次类目兜底的表格批量铺货
|
||||
- 接入 OpenAI 兼容接口实现可控的 AI 客服回复
|
||||
- 账号掉线、风控、续期和发货结果的多渠道通知
|
||||
|
||||
@@ -60,7 +60,7 @@ Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名
|
||||
| 即时消息 | 闲鱼 WebSocket 长连接、消息收发、关键词回复、默认回复及仅回复一次 |
|
||||
| 自动化中心 | 付款后自动发货、评价后赠品、超时未评价提醒、失败任务恢复与幂等检查点 |
|
||||
| 卡密库存 | 文本、批量卡密和图片三种交付类型,库存追加、批量导入、规格与延迟发送 |
|
||||
| 商品管理 | 商品同步、手工关联、单商品发布、CSV + ZIP 批量铺货、任务恢复与结果导出 |
|
||||
| 商品管理 | 商品同步、手工关联、单商品发布、CSV + ZIP 批量铺货、自动识别失败时的逐行/批次类目兜底、任务恢复与结果导出 |
|
||||
| 订单管理 | 订单同步、插入、编辑、平台发货、补发卡密、仅确认发货及异常状态处理 |
|
||||
| AI 回复 | OpenAI 兼容 API、模型发现、自定义提示词、议价轮次和让价范围控制 |
|
||||
| 数据看板 | 活跃账号、订单、营收、库存、商品销量与金额统计 |
|
||||
|
||||
+1
-1
@@ -1004,7 +1004,7 @@
|
||||
<div class="feature-card">
|
||||
<div class="feature-icon-box">📊</div>
|
||||
<h3 class="feature-card-title">批量铺货与商品管理</h3>
|
||||
<p class="feature-card-desc">轻松同步闲鱼在售商品,支持 CSV + ZIP 素材包批量生成发布,单商品手动挂载及关联自动化发货规则。</p>
|
||||
<p class="feature-card-desc">轻松同步闲鱼在售商品,支持 CSV + ZIP 素材包批量发布、逐行与批次类目兜底、单商品手动挂载及自动化发货规则。</p>
|
||||
</div>
|
||||
|
||||
<!-- Card 7 -->
|
||||
|
||||
+18
-7
@@ -9,7 +9,7 @@
|
||||
推荐中文表头:
|
||||
|
||||
```text
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,类目ID,类目名称,频道类目ID,淘宝类目ID,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
```
|
||||
|
||||
也支持英文表头,但不能与中文混用。每行一个商品;`账号ID` 可留空并在上传页选择默认账号。
|
||||
@@ -19,6 +19,8 @@
|
||||
- 标题非空,价格大于 0;库存为正整数,留空默认 1。
|
||||
- 邮费模式为 `free`/`包邮` 或 `fixed`/`固定邮费`;固定邮费时必须填邮费。
|
||||
- 每件商品 1–9 张图片,多个用英文分号 `;` 分隔。可用公开 `https://` URL,或 ZIP 内相对路径。
|
||||
- 上传页必须填写“批次兜底类目 ID + 类目名称”。表格的“类目ID + 类目名称”可选,用于覆盖某一行的批次兜底配置;两列必须同时填写。
|
||||
- “频道类目ID”和“淘宝类目ID”通常留空,只有已取得同类闲鱼商品的准确值时才填写。
|
||||
- 本地图片 ZIP 最大 200 MiB,单图最大 10 MiB;表格最大 20 MiB。
|
||||
- CSV 使用 UTF-8,建议带 BOM;不要在表头增加空格。
|
||||
|
||||
@@ -37,15 +39,24 @@
|
||||
## 2. 后台操作
|
||||
|
||||
1. 在“商品管理”点击“批量铺货”。
|
||||
2. 选择表格;表格引用本地图片时同时选择 ZIP。
|
||||
3. 未填账号 ID 时,在页面选择默认账号。
|
||||
4. 点击预检,逐行处理错误。常见错误是账号未授权、卡密组不存在、图片路径不匹配、固定邮费缺失或价格为 0。
|
||||
5. 所有需发布行确认无误后启动任务;不要关闭正在运行的任务页面。
|
||||
6. 在任务详情查看成功、失败与进行中行。需要时取消任务;正在提交的单件商品可能继续完成。
|
||||
7. 对可重试失败项使用“重试失败”,并下载结果 CSV 留档。
|
||||
2. 选择默认账号;表格某行未填账号 ID 时会使用它。
|
||||
3. 填写批次兜底类目 ID 和名称。优先从同类型、已经同步或发布成功的历史商品复用,页面会提示已知的历史类目。
|
||||
4. 选择表格;表格引用本地图片时同时选择 ZIP。
|
||||
5. 点击预检,确认每一行显示的兜底类目正确,再处理账号未授权、卡密组不存在、图片路径不匹配、固定邮费缺失或价格为 0 等错误。
|
||||
6. 所有需发布行确认无误后启动任务;不要关闭正在运行的任务页面。
|
||||
7. 在任务详情查看成功、失败与进行中行。需要时取消任务;正在提交的单件商品可能继续完成。
|
||||
8. 对可重试失败项使用“重试失败”,并下载结果 CSV 留档。
|
||||
|
||||
### 类目选择顺序
|
||||
|
||||
系统仍会先让闲鱼根据标题、描述和图片自动识别类目。只有闲鱼明确返回“未能自动识别商品类目”时,系统才会使用后备配置:优先使用表格当前行的“类目ID + 类目名称”,否则使用上传页的批次兜底类目。接口超时、鉴权失败、风控等错误不会被兜底类目掩盖。
|
||||
|
||||
批量铺货发布的都是虚拟商品,不请求或提交实物发货地址;指定类目只解决商品类型识别,不会改变虚拟发货流程。
|
||||
|
||||
## 3. 常见问题
|
||||
|
||||
- **图片找不到**:ZIP 内路径必须与表格完全一致,使用 `/`,不能以 `/` 开头或包含 `..`。
|
||||
- **未能自动识别类目**:新建批次时必须设置兜底类目;如果仍出现该提示,通常是旧批次没有保存兜底配置,请重新上传创建任务。不要把接口超时或鉴权错误误当成类目问题。
|
||||
- **类目 ID 从哪里取**:优先复用账号里同类型的历史商品类目。选择页面给出的历史类目,或从已同步商品的类目信息中复制 ID 和准确名称;不要猜测 ID。
|
||||
- **自动化不生效**:检查卡密组 ID、账号归属、启用列和库存;发布成功后仍应查看自动化规则是否已创建。
|
||||
- **任务中断**:先重新打开批次详情确认状态,避免重复新建整批任务;仅重试失败行。
|
||||
@@ -31,12 +31,15 @@
|
||||
|
||||
- 对已在闲鱼上存在的商品,选择同步全部或按页同步,确认商品归属到正确账号。
|
||||
- 对单个新商品,使用发布入口填写标题、描述、价格、库存、邮费和图片。图片必须可用;提交前复核目标账号。
|
||||
- 批量铺货时必须指定批次兜底类目 ID 和名称。系统优先使用闲鱼自动识别结果,仅在无法识别时使用表格当前行的指定类目或批次兜底类目;类目信息应复用同类型历史商品,不要猜测 ID。
|
||||
- 批量铺货商品按虚拟商品发布,不依赖实物发货地址;类目兜底不会改变付款后的虚拟交付逻辑。
|
||||
- 商品发布成功不等于已开启自动发货。仍需在“自动化规则”中按商品/规格绑定卡密组,或在批量铺货表格中一并声明自动化配置。
|
||||
|
||||
## 4. 上线前检查
|
||||
|
||||
1. 账号在线并已启用。
|
||||
2. 商品已同步或发布成功,价格、库存和图片正确。
|
||||
3. 所需卡密组启用且余量充足。
|
||||
4. 自动化规则准确匹配商品;有规格时逐个规格确认。
|
||||
5. 先用测试订单验证,检查订单列表、自动化异常列表和通知记录。
|
||||
3. 批量铺货的预检明细已显示正确的逐行兜底类目。
|
||||
4. 所需卡密组启用且余量充足。
|
||||
5. 自动化规则准确匹配商品;有规格时逐个规格确认。
|
||||
6. 先用测试订单验证,检查订单列表、自动化异常列表和通知记录。
|
||||
+28
-8
@@ -28,13 +28,13 @@
|
||||
表头必须完全一致(大小写敏感、无空格)。**推荐用中文表头**,复制下面这一行:
|
||||
|
||||
```
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,类目ID,类目名称,频道类目ID,淘宝类目ID,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
```
|
||||
|
||||
如果用英文表头,对应是:
|
||||
|
||||
```
|
||||
cookie_id,title,description,price,original_price,quantity,postage_mode,postage,images,paid_delivery_enabled,paid_delivery_contents,review_gift_enabled,review_gift_contents,review_request_enabled,review_request_after_hours,review_request_message,review_request_max_attempts
|
||||
cookie_id,title,description,price,original_price,quantity,postage_mode,postage,images,category_id,category_name,channel_category_id,tb_category_id,paid_delivery_enabled,paid_delivery_contents,review_gift_enabled,review_gift_contents,review_request_enabled,review_request_after_hours,review_request_message,review_request_max_attempts
|
||||
```
|
||||
|
||||
> 中英文表头二选一,**不要混用**。每个表头单元格的匹配是精确匹配,多空格、全角半角差异都会导致该列识别失败。
|
||||
@@ -55,6 +55,23 @@ cookie_id,title,description,price,original_price,quantity,postage_mode,postage,i
|
||||
| 邮费 | 条件必填 | 数字。邮费模式为 `fixed` 时必填;`free` 时留空 | `8.00` |
|
||||
| 图片 | 是 | 1–9 张,多个用 `;` 分隔。每项是公网 URL 或图片包内相对路径 | `images/bundle-1.jpg;images/bundle-2.jpg` |
|
||||
|
||||
#### 指定类目字段(可选的逐行兜底)
|
||||
|
||||
| 列 | 何时填写 | 格式 / 取值 |
|
||||
|---|---|---|
|
||||
| 类目ID | 当前行需要覆盖批次兜底类目时 | 闲鱼商品类目 ID;必须和“类目名称”同时填写 |
|
||||
| 类目名称 | 填写了“类目ID”时 | 与类目 ID 对应的准确名称 |
|
||||
| 频道类目ID | 通常留空 | 仅在已从同类闲鱼商品取得准确值时填写 |
|
||||
| 淘宝类目ID | 通常留空 | 仅在已从同类闲鱼商品取得准确值时填写 |
|
||||
|
||||
上传页面还会要求运营人员填写一个必需的“批次兜底类目 ID + 类目名称”。系统对每行按以下顺序处理:
|
||||
|
||||
1. 先调用闲鱼接口,根据标题、描述和图片自动识别类目。
|
||||
2. 自动识别成功时,使用闲鱼返回的类目,指定类目不会强行覆盖。
|
||||
3. 只有闲鱼明确未识别出类目时,才使用表格当前行的指定类目;当前行未填时使用上传页的批次兜底类目。
|
||||
|
||||
因此,即使表格完全不填写这四列,运营人员也必须在上传页设置批次兜底类目,保证每个待发布商品都有可用的后备类型。类目 ID 和名称应从同类型、已经同步或发布成功的闲鱼商品中取得,不要凭空编造。频道类目 ID 和淘宝类目 ID 没有可靠值时留空即可。
|
||||
|
||||
#### 自动化字段(可选,不填或填"否"表示不启用)
|
||||
|
||||
启用值接受:`1` / `true` / `yes` / `y` / `on` / `是` / `开启` / `启用`(不区分大小写)。
|
||||
@@ -152,6 +169,7 @@ sub/product.jpg
|
||||
| 邮费模式 | `free` 或 `fixed`(或 `包邮` / `固定邮费`) |
|
||||
| 邮费 | 邮费模式为 `fixed` 时必填且 ≥ 0 |
|
||||
| 图片 | 1–9 张;本地路径必须在 ZIP 内存在;URL 必须是合法 `http(s)://` |
|
||||
| 指定类目 | 当前行填写了任一类目字段时,“类目ID”和“类目名称”必须同时存在;批次兜底类目由上传者在页面必填 |
|
||||
| 付款发货 | 启用时:内容列必填至少一条卡密组;卡密组 ID 必须属于上传者;每件份数 > 0;延迟秒 ≥ 0 |
|
||||
| 评价赠品 | 同上 |
|
||||
| 求评价 | 启用时:等待小时 > 0、文案非空、最多次数 > 0 |
|
||||
@@ -178,19 +196,19 @@ sub/product.jpg
|
||||
|
||||
**表格 `商品清单.csv`:**
|
||||
```csv
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
2222660684687,普通商品,仅发布不绑自动化,49.90,,10,fixed,8.00,https://cdn.example.com/p1.jpg,否,,,,否,,,
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,类目ID,类目名称,频道类目ID,淘宝类目ID,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
2222660684687,普通商品,仅发布不绑自动化,49.90,,10,fixed,8.00,https://cdn.example.com/p1.jpg,,,,,否,,否,,否,,,
|
||||
```
|
||||
|
||||
无需图片包(用的是 URL)。
|
||||
无需图片包(用的是 URL)。四个逐行类目列留空,上传时必须选择同类型商品对应的批次兜底类目。
|
||||
|
||||
### 7.2 完整自动化 + 本地图片包
|
||||
|
||||
**表格 `商品清单.csv`:**
|
||||
```csv
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
2222660684687,会员组合包自动发货,下单后发送主卡和附赠卡。,19.90,29.90,10,free,,images/bundle-1.jpg;images/bundle-2.jpg,是,101:1;102:1,是,201:1;202:2,是,72,亲,满意的话麻烦给个评价,谢谢~,1
|
||||
2222660684687,单卡直发,拍下自动发卡。,9.90,,50,free,,images/single.jpg,是,101:1,否,,否,,,
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,类目ID,类目名称,频道类目ID,淘宝类目ID,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
2222660684687,会员组合包自动发货,下单后发送主卡和附赠卡。,19.90,29.90,10,free,,images/bundle-1.jpg;images/bundle-2.jpg,,,,,是,101:1;102:1,是,201:1;202:2,是,72,亲,满意的话麻烦给个评价,谢谢~,1
|
||||
2222660684687,单卡直发,拍下自动发卡。,9.90,,50,free,,images/single.jpg,,,,,是,101:1,否,,否,,,
|
||||
```
|
||||
|
||||
**图片包 `images.zip`:**
|
||||
@@ -215,6 +233,8 @@ images.zip
|
||||
- [ ] 每行标题非空、价格 > 0、库存 > 0
|
||||
- [ ] 邮费模式只填 `free` / `fixed`(或 `包邮` / `固定邮费`);`fixed` 时邮费已填
|
||||
- [ ] 每行图片 1–9 张,多个用 `;` 分隔
|
||||
- [ ] 已确认上传者会填写准确的批次兜底类目 ID 和名称
|
||||
- [ ] 需要逐行覆盖类目时,“类目ID”和“类目名称”同时填写;没有可靠的频道/淘宝类目 ID 时保持为空
|
||||
- [ ] 用本地路径的图片,在 ZIP 内对应路径都能找到
|
||||
- [ ] 用 URL 的图片,链接是 `http(s)://` 且可公开访问
|
||||
- [ ] 启用了付款发货/评价赠品的行,内容列按 §3 格式填写,卡密组 ID 已知(或已标注需运营补填)
|
||||
|
||||
@@ -27,6 +27,13 @@ interface ItemListProps {
|
||||
|
||||
type BatchPhase = 'upload' | 'preview' | 'running' | 'done';
|
||||
|
||||
interface PublishCategory {
|
||||
cat_id: string;
|
||||
cat_name: string;
|
||||
channel_cat_id?: string;
|
||||
tb_cat_id?: string;
|
||||
}
|
||||
|
||||
interface PublishBatchPreviewRow {
|
||||
row_no: number;
|
||||
valid: boolean;
|
||||
@@ -36,6 +43,7 @@ interface PublishBatchPreviewRow {
|
||||
price: string;
|
||||
quantity: number;
|
||||
images: string[];
|
||||
category: PublishCategory;
|
||||
}
|
||||
|
||||
interface PublishBatchDetailRow {
|
||||
@@ -51,6 +59,7 @@ interface PublishBatchDetailRow {
|
||||
error_message: string;
|
||||
failure_kind: string;
|
||||
images?: string[];
|
||||
category: PublishCategory;
|
||||
}
|
||||
|
||||
interface PublishBatchDetail {
|
||||
@@ -88,6 +97,12 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const [batchPhase, setBatchPhase] = useState<BatchPhase>('upload');
|
||||
const [batchFile, setBatchFile] = useState<File | null>(null);
|
||||
const [batchImagesZip, setBatchImagesZip] = useState<File | null>(null);
|
||||
const [batchFallbackCategory, setBatchFallbackCategory] = useState({
|
||||
catId: '',
|
||||
catName: '',
|
||||
channelCatId: '',
|
||||
tbCatId: '',
|
||||
});
|
||||
const [batchPreview, setBatchPreview] = useState<{
|
||||
preview_id: string;
|
||||
total: number;
|
||||
@@ -120,6 +135,23 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
});
|
||||
const [publishImagePreviews, setPublishImagePreviews] = useState<{ key: string; url: string }[]>([]);
|
||||
|
||||
const knownCategories = useMemo(() => {
|
||||
const unique = new Map<string, string>();
|
||||
items.forEach(item => {
|
||||
const catId = String(item.item_category || '').trim();
|
||||
if (!catId) return;
|
||||
let catName = '';
|
||||
try {
|
||||
const detail = JSON.parse(item.item_detail || '{}') as { category_name?: string };
|
||||
catName = String(detail.category_name || '').trim();
|
||||
} catch {
|
||||
// 历史商品详情可能不是 JSON,仍保留可复用的类目 ID。
|
||||
}
|
||||
if (!unique.has(catId) || catName) unique.set(catId, catName);
|
||||
});
|
||||
return Array.from(unique, ([catId, catName]) => ({ catId, catName }));
|
||||
}, [items]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showPublishModal || publishForm.images.length === 0) {
|
||||
setPublishImagePreviews([]);
|
||||
@@ -319,6 +351,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
setBatchDetail(null);
|
||||
setBatchFile(null);
|
||||
setBatchImagesZip(null);
|
||||
setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' });
|
||||
setShowBatchModal(true);
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
@@ -355,12 +388,16 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const handlePreviewBatch = async () => {
|
||||
if (!batchFile) return alert('请先上传商品表格');
|
||||
if (!selectedAccount) return alert('请先选择默认发布账号');
|
||||
if (!batchFallbackCategory.catId.trim() || !batchFallbackCategory.catName.trim()) {
|
||||
return alert('请同时填写批次兜底类目 ID 和类目名称');
|
||||
}
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
const result = await previewItemPublishBatch({
|
||||
file: batchFile,
|
||||
imagesZip: batchImagesZip,
|
||||
defaultCookieId: selectedAccount,
|
||||
fallbackCategory: batchFallbackCategory,
|
||||
});
|
||||
setBatchPreview(result);
|
||||
setBatchDetail(null);
|
||||
@@ -442,12 +479,13 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const downloadPublishTemplate = () => {
|
||||
const headers = [
|
||||
'账号ID', '标题', '描述', '价格', '原价', '库存', '邮费模式', '邮费', '图片',
|
||||
'类目ID', '类目名称', '频道类目ID', '淘宝类目ID',
|
||||
'付款发货启用', '付款发货内容', '评价赠品启用', '评价赠品内容',
|
||||
'求评价启用', '求评价等待小时', '求评价文案', '求评价最多次数',
|
||||
];
|
||||
const rows = [
|
||||
['', '会员组合包自动发货', '下单后发送主卡和附赠卡。', '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', '否', '', '否', '', '否', '', '', ''],
|
||||
['', '会员组合包自动发货', '下单后发送主卡和附赠卡。', '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(','))
|
||||
@@ -915,6 +953,60 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<p className="text-xs text-gray-500">表格中“账号ID”为空时,会使用这里选择的账号。</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-amber-200 bg-amber-50/70 p-4 space-y-3">
|
||||
<div>
|
||||
<div className="text-sm font-extrabold text-gray-900">批次兜底类目 <span className="text-red-600">*</span></div>
|
||||
<p className="mt-1 text-xs leading-5 text-amber-800">闲鱼仍会先自动识别;只有明确识别不出类目时才使用这里的配置。表格中的“类目ID + 类目名称”可覆盖当前行。</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-xs font-bold text-gray-700">类目 ID</span>
|
||||
<input
|
||||
className="w-full ios-input px-3 py-2.5 rounded-xl bg-white"
|
||||
list="known-publish-categories"
|
||||
placeholder="例如 50023717"
|
||||
value={batchFallbackCategory.catId}
|
||||
onChange={e => {
|
||||
const catId = e.target.value;
|
||||
const matched = knownCategories.find(category => category.catId === catId.trim());
|
||||
setBatchFallbackCategory(prev => ({
|
||||
...prev,
|
||||
catId,
|
||||
catName: matched?.catName || (catId ? prev.catName : ''),
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<datalist id="known-publish-categories">
|
||||
{knownCategories.map(category => (
|
||||
<option key={category.catId} value={category.catId}>{category.catName || '历史商品类目'}</option>
|
||||
))}
|
||||
</datalist>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-xs font-bold text-gray-700">类目名称</span>
|
||||
<input
|
||||
className="w-full ios-input px-3 py-2.5 rounded-xl bg-white"
|
||||
placeholder="例如 其他虚拟商品"
|
||||
value={batchFallbackCategory.catName}
|
||||
onChange={e => setBatchFallbackCategory(prev => ({ ...prev, catName: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<details className="group text-xs text-gray-600">
|
||||
<summary className="cursor-pointer select-none font-bold text-amber-900">高级类目字段(通常留空)</summary>
|
||||
<div className="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<label className="space-y-1.5">
|
||||
<span className="font-bold text-gray-700">频道类目 ID</span>
|
||||
<input className="w-full ios-input px-3 py-2.5 rounded-xl bg-white" value={batchFallbackCategory.channelCatId} onChange={e => setBatchFallbackCategory(prev => ({ ...prev, channelCatId: e.target.value }))} />
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="font-bold text-gray-700">淘宝类目 ID</span>
|
||||
<input className="w-full ios-input px-3 py-2.5 rounded-xl bg-white" value={batchFallbackCategory.tbCatId} onChange={e => setBatchFallbackCategory(prev => ({ ...prev, tbCatId: e.target.value }))} />
|
||||
</label>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors">
|
||||
<UploadCloud className="w-9 h-9 text-blue-600 mb-3" />
|
||||
@@ -986,6 +1078,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
['邮费模式', '可以留空', '留空表示包邮;包邮填 free,固定邮费填 fixed'],
|
||||
['邮费', '邮费模式填 fixed 时填写', '只填数字,例如 8.00'],
|
||||
['图片', '每个商品都要填', '填写 zip 内图片路径或图片网址;多张图片用英文分号隔开'],
|
||||
['类目ID', '需要覆盖批次兜底类目时填写', '必须和“类目名称”同时填写;只覆盖当前商品行'],
|
||||
['类目名称', '填写了“类目ID”时必填', '填写该 ID 对应的准确类目名称'],
|
||||
['频道类目ID', '通常留空', '仅在已明确取得闲鱼频道类目 ID 时填写'],
|
||||
['淘宝类目ID', '通常留空', '仅在已明确取得淘宝类目 ID 时填写'],
|
||||
['付款发货启用', '需要付款后自动发货时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['付款发货内容', '“付款发货启用”填“是”时填写', '从“卡密库存”页面取得卡密组 ID,按上方示例填写'],
|
||||
['评价赠品启用', '需要评价赠品时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
@@ -1033,6 +1129,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<th className="px-4 py-3">状态</th>
|
||||
<th className="px-4 py-3">标题</th>
|
||||
<th className="px-4 py-3">价格/库存</th>
|
||||
<th className="px-4 py-3">兜底类目</th>
|
||||
<th className="px-4 py-3">图片</th>
|
||||
<th className="px-4 py-3">问题</th>
|
||||
</tr>
|
||||
@@ -1048,6 +1145,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</td>
|
||||
<td className="px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate">{row.title || '-'}</td>
|
||||
<td className="px-4 py-3 text-gray-600">¥{row.price || '-'} / {row.quantity || 1}</td>
|
||||
<td className="px-4 py-3 text-xs text-gray-600 min-w-[150px]">
|
||||
<div className="font-bold text-gray-800">{row.category?.cat_name || '-'}</div>
|
||||
<div className="font-mono text-gray-400">{row.category?.cat_id || '-'}</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-600">{row.images?.length || 0} 张</td>
|
||||
<td className="px-4 py-3 text-red-600 text-xs max-w-[280px]">{row.errors?.join(';') || '-'}</td>
|
||||
</tr>
|
||||
@@ -1090,6 +1191,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<th className="px-4 py-3">行号</th>
|
||||
<th className="px-4 py-3">状态</th>
|
||||
<th className="px-4 py-3">标题</th>
|
||||
<th className="px-4 py-3">兜底类目</th>
|
||||
<th className="px-4 py-3">商品ID</th>
|
||||
<th className="px-4 py-3">错误原因</th>
|
||||
</tr>
|
||||
@@ -1104,6 +1206,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate">{row.title}</td>
|
||||
<td className="px-4 py-3 text-xs text-gray-600 min-w-[150px]">
|
||||
<div className="font-bold text-gray-800">{row.category?.cat_name || '-'}</div>
|
||||
<div className="font-mono text-gray-400">{row.category?.cat_id || '-'}</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs font-mono">
|
||||
{row.item_url ? <a href={row.item_url} target="_blank" rel="noreferrer" className="text-blue-600 hover:underline">{row.item_id}</a> : (row.item_id || '-')}
|
||||
</td>
|
||||
@@ -1119,7 +1225,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
|
||||
<div className="modal-footer">
|
||||
{batchPhase === 'upload' && (
|
||||
<button disabled={batchLoading || !batchFile || !selectedAccount} onClick={handlePreviewBatch} className="w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50">
|
||||
<button disabled={batchLoading || !batchFile || !selectedAccount || !batchFallbackCategory.catId.trim() || !batchFallbackCategory.catName.trim()} onClick={handlePreviewBatch} className="w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50">
|
||||
<RefreshCw className={`w-4 h-4 ${batchLoading ? 'animate-spin' : ''}`} />
|
||||
{batchLoading ? '正在预检...' : '开始预检'}
|
||||
</button>
|
||||
|
||||
+209
-25
@@ -24,6 +24,7 @@ import {
|
||||
getAutomationIssues,
|
||||
getReplyRules,
|
||||
getShippingRules,
|
||||
getShippingRulesPage,
|
||||
updateDefaultReply,
|
||||
updateReplyRule,
|
||||
updateShippingRule,
|
||||
@@ -36,6 +37,8 @@ import {
|
||||
AlertCircle,
|
||||
Bot,
|
||||
CheckCircle2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Clock3,
|
||||
Edit,
|
||||
Gift,
|
||||
@@ -45,7 +48,9 @@ import {
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Save,
|
||||
Search,
|
||||
Send,
|
||||
SlidersHorizontal,
|
||||
Trash2,
|
||||
X,
|
||||
Zap,
|
||||
@@ -54,7 +59,6 @@ import {
|
||||
automationIssueKindLabel,
|
||||
canResolveAutomationIssue,
|
||||
filterAutomationIssues,
|
||||
loadAutomationPageData,
|
||||
} from './automationIssueState';
|
||||
import { commitIfLatest } from './latestRequest';
|
||||
|
||||
@@ -220,6 +224,15 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selectedAccountId, setSelectedAccountId] = useState('');
|
||||
const [automationSearch, setAutomationSearch] = useState('');
|
||||
const [debouncedAutomationSearch, setDebouncedAutomationSearch] = useState('');
|
||||
const [automationTriggerFilter, setAutomationTriggerFilter] = useState<AutomationTriggerType | ''>('');
|
||||
const [automationStatusFilter, setAutomationStatusFilter] = useState<'all' | 'enabled' | 'disabled'>('all');
|
||||
const [automationPage, setAutomationPage] = useState(1);
|
||||
const [automationPageSize, setAutomationPageSize] = useState(10);
|
||||
const [automationTotal, setAutomationTotal] = useState(0);
|
||||
const [automationTotalPages, setAutomationTotalPages] = useState(0);
|
||||
const automationRulesRequest = useRef(0);
|
||||
const replyRulesRequest = useRef(0);
|
||||
const selectedAccountRef = useRef('');
|
||||
selectedAccountRef.current = selectedAccountId;
|
||||
@@ -253,14 +266,28 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
}, []);
|
||||
|
||||
const loadAutomationRules = useCallback(async () => {
|
||||
await loadAutomationPageData({
|
||||
loadRules: getShippingRules,
|
||||
loadIssues: getAutomationIssues,
|
||||
onRules: setAutomationRules,
|
||||
onIssues: setAutomationIssues,
|
||||
onIssuesError: error => console.warn('加载自动化异常列表失败,不阻断规则展示', error),
|
||||
const requestID = ++automationRulesRequest.current;
|
||||
const issuesPromise = getAutomationIssues().catch(error => {
|
||||
console.warn('加载自动化异常列表失败,不阻断规则展示', error);
|
||||
return null;
|
||||
});
|
||||
}, []);
|
||||
const result = await getShippingRulesPage({
|
||||
cookieId: selectedAccountId || undefined,
|
||||
triggerType: automationTriggerFilter,
|
||||
enabled: automationStatusFilter === 'all' ? undefined : automationStatusFilter === 'enabled',
|
||||
search: debouncedAutomationSearch,
|
||||
page: automationPage,
|
||||
pageSize: automationPageSize,
|
||||
});
|
||||
if (requestID !== automationRulesRequest.current) return;
|
||||
setAutomationRules(result.data);
|
||||
setAutomationTotal(result.total);
|
||||
setAutomationTotalPages(result.total_pages);
|
||||
if (result.page !== automationPage) setAutomationPage(result.page);
|
||||
const issues = await issuesPromise;
|
||||
if (requestID !== automationRulesRequest.current) return;
|
||||
if (issues) setAutomationIssues(issues);
|
||||
}, [automationPage, automationPageSize, automationStatusFilter, automationTriggerFilter, debouncedAutomationSearch, selectedAccountId]);
|
||||
|
||||
const loadReplyRules = useCallback(async () => {
|
||||
const cookieID = selectedAccountId;
|
||||
@@ -293,6 +320,14 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
}
|
||||
}, [activeTab, loadAutomationRules, loadDefaultReplies, loadReplyRules]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setAutomationPage(1);
|
||||
setDebouncedAutomationSearch(automationSearch.trim());
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [automationSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadReferenceData().catch(error => console.error('加载规则参考数据失败', error));
|
||||
}, [loadReferenceData]);
|
||||
@@ -328,6 +363,25 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
return grouped;
|
||||
}, [visibleAutomationRules]);
|
||||
|
||||
const automationPageNumbers = useMemo(() => {
|
||||
if (automationTotalPages <= 1) return [];
|
||||
const first = Math.max(1, Math.min(automationPage - 2, automationTotalPages - 4));
|
||||
const last = Math.min(automationTotalPages, first + 4);
|
||||
return Array.from({ length: last - first + 1 }, (_, index) => first + index);
|
||||
}, [automationPage, automationTotalPages]);
|
||||
|
||||
const hasAutomationListFilters = Boolean(
|
||||
automationSearch.trim() || automationTriggerFilter || automationStatusFilter !== 'all',
|
||||
);
|
||||
|
||||
const clearAutomationListFilters = () => {
|
||||
setAutomationSearch('');
|
||||
setDebouncedAutomationSearch('');
|
||||
setAutomationTriggerFilter('');
|
||||
setAutomationStatusFilter('all');
|
||||
setAutomationPage(1);
|
||||
};
|
||||
|
||||
const modalAccountItems = useMemo(() => {
|
||||
const cookieID = editingAutomationRule?.cookie_id || selectedAccountId;
|
||||
return items.filter(item => item.cookie_id === cookieID);
|
||||
@@ -748,15 +802,18 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-fade-in">
|
||||
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
|
||||
<div className="flex flex-col xl:flex-row justify-between xl:items-end gap-4">
|
||||
<div>
|
||||
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">自动化规则</h2>
|
||||
<p className="text-gray-500 mt-2 font-medium">系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。</p>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<div className="flex flex-col sm:flex-row sm:flex-wrap gap-3">
|
||||
<select
|
||||
value={selectedAccountId}
|
||||
onChange={event => setSelectedAccountId(event.target.value)}
|
||||
onChange={event => {
|
||||
setSelectedAccountId(event.target.value);
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input px-4 py-3 rounded-2xl text-sm min-w-64"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
@@ -766,7 +823,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</select>
|
||||
<button
|
||||
onClick={refresh}
|
||||
className="px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 transition-colors"
|
||||
className="px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 whitespace-nowrap transition-colors"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
刷新
|
||||
@@ -774,7 +831,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
<button
|
||||
onClick={activeTab === 'automation' ? () => openNewAutomationRule('order_paid') : activeTab === 'reply' ? handleAddReplyRule : () => void openDefaultReplyModal()}
|
||||
disabled={!selectedAccountId}
|
||||
className="ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 disabled:opacity-50"
|
||||
className="ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
{primaryActionLabel}
|
||||
@@ -879,7 +936,10 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm">
|
||||
<h3 className="font-black text-gray-900 mb-4">规则概览</h3>
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<h3 className="font-black text-gray-900">本页规则构成</h3>
|
||||
<span className="text-xs font-bold text-gray-400">共 {automationTotal} 条</span>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{triggerOrder.map(trigger => {
|
||||
const meta = triggerMeta[trigger];
|
||||
@@ -898,15 +958,82 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section className="space-y-4">
|
||||
{visibleAutomationRules.length === 0 ? (
|
||||
<div className="bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center">
|
||||
<Zap className="w-12 h-12 text-gray-300 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-black text-gray-900">还没有自动化规则</h3>
|
||||
<p className="text-gray-500 mt-2">从左侧选择一个模板开始配置。</p>
|
||||
</div>
|
||||
) : (
|
||||
visibleAutomationRules.map(rule => {
|
||||
<section className="space-y-4">
|
||||
<div className="rounded-xl border border-gray-100 bg-[#FAFAFA] p-4 shadow-sm">
|
||||
<div className="flex flex-col gap-3 xl:flex-row xl:items-center">
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="search"
|
||||
aria-label="搜索自动化规则"
|
||||
placeholder="搜索规则名、商品名或商品 ID..."
|
||||
value={automationSearch}
|
||||
onChange={event => {
|
||||
setAutomationSearch(event.target.value);
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative xl:w-52">
|
||||
<SlidersHorizontal className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<select
|
||||
aria-label="按自动化类型筛选"
|
||||
value={automationTriggerFilter}
|
||||
onChange={event => {
|
||||
setAutomationTriggerFilter(event.target.value as AutomationTriggerType | '');
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm"
|
||||
>
|
||||
<option value="">全部自动化类型</option>
|
||||
{triggerOrder.map(trigger => <option key={trigger} value={trigger}>{triggerMeta[trigger].shortLabel}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<select
|
||||
aria-label="按启用状态筛选"
|
||||
value={automationStatusFilter}
|
||||
onChange={event => {
|
||||
setAutomationStatusFilter(event.target.value as 'all' | 'enabled' | 'disabled');
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36"
|
||||
>
|
||||
<option value="all">全部状态</option>
|
||||
<option value="enabled">已启用</option>
|
||||
<option value="disabled">已禁用</option>
|
||||
</select>
|
||||
{hasAutomationListFilters && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={clearAutomationListFilters}
|
||||
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900"
|
||||
title="清除筛选"
|
||||
aria-label="清除筛选"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-3 flex items-center justify-between text-xs font-bold text-gray-400">
|
||||
<span>找到 {automationTotal} 条规则</span>
|
||||
{loading && <span className="inline-flex items-center gap-1.5"><RefreshCw className="h-3.5 w-3.5 animate-spin" />正在更新</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && visibleAutomationRules.length === 0 ? (
|
||||
<div className="flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400">
|
||||
<RefreshCw className="mr-2 h-4 w-4 animate-spin" />
|
||||
正在加载规则
|
||||
</div>
|
||||
) : visibleAutomationRules.length === 0 ? (
|
||||
<div className="bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center">
|
||||
<Zap className="w-12 h-12 text-gray-300 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-black text-gray-900">{hasAutomationListFilters ? '没有匹配的自动化规则' : '还没有自动化规则'}</h3>
|
||||
<p className="text-gray-500 mt-2">{hasAutomationListFilters ? '调整或清除筛选条件后再试。' : '从左侧选择一个模板开始配置。'}</p>
|
||||
</div>
|
||||
) : (
|
||||
visibleAutomationRules.map(rule => {
|
||||
const meta = triggerMeta[rule.trigger_type];
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
@@ -957,8 +1084,65 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</article>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{automationTotal > 0 && (
|
||||
<div className="flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-3 text-sm font-medium text-gray-500">
|
||||
<span>第 {automationPage} / {Math.max(automationTotalPages, 1)} 页</span>
|
||||
<span className="h-4 w-px bg-gray-200" />
|
||||
<label className="flex items-center gap-2">
|
||||
<span className="sr-only">每页显示数量</span>
|
||||
<select
|
||||
value={automationPageSize}
|
||||
onChange={event => {
|
||||
setAutomationPageSize(Number(event.target.value));
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm"
|
||||
>
|
||||
{[10, 20, 50].map(size => <option key={size} value={size}>{size} 条/页</option>)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={automationPage <= 1 || loading}
|
||||
onClick={() => setAutomationPage(page => Math.max(1, page - 1))}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
aria-label="上一页"
|
||||
title="上一页"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
{automationPageNumbers.map(pageNumber => (
|
||||
<button
|
||||
key={pageNumber}
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => setAutomationPage(pageNumber)}
|
||||
className={`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${pageNumber === automationPage ? 'bg-[#0094f7] text-white' : 'bg-gray-50 text-gray-600 hover:bg-gray-100'} disabled:cursor-not-allowed disabled:opacity-60`}
|
||||
aria-label={`第 ${pageNumber} 页`}
|
||||
aria-current={pageNumber === automationPage ? 'page' : undefined}
|
||||
>
|
||||
{pageNumber}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
disabled={automationPage >= automationTotalPages || loading}
|
||||
onClick={() => setAutomationPage(page => Math.min(automationTotalPages, page + 1))}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
aria-label="下一页"
|
||||
title="下一页"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
getOrderAnalytics,
|
||||
getReplyRules,
|
||||
getShippingRules,
|
||||
getShippingRulesPage,
|
||||
getSystemSettings,
|
||||
getValidOrders,
|
||||
logout,
|
||||
@@ -108,6 +109,33 @@ test('getOrders maps unsupported backend statuses to unknown', async () => {
|
||||
expect(result.data[0].status).toBe('unknown');
|
||||
});
|
||||
|
||||
test('getShippingRulesPage sends filters and preserves pagination metadata', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
data: [{ id: 7, name: '付款规则', trigger_type: 'order_paid', enabled: false, actions: [] }],
|
||||
total: 21,
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
total_pages: 2,
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const result = await getShippingRulesPage({
|
||||
cookieId: 'acc1',
|
||||
triggerType: 'order_paid',
|
||||
enabled: false,
|
||||
search: ' 商品 ',
|
||||
page: 2,
|
||||
pageSize: 20,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ total: 21, page: 2, page_size: 20, total_pages: 2 });
|
||||
expect(result.data[0]).toMatchObject({ id: '7', name: '付款规则', enabled: false });
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/automation-rules?page=2&page_size=20&cookie_id=acc1&trigger_type=order_paid&enabled=false&search=%E5%95%86%E5%93%81',
|
||||
expect.objectContaining({ method: 'GET', credentials: 'include' }),
|
||||
);
|
||||
});
|
||||
|
||||
test('getValidOrders accepts wrapped responses', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o2', order_status: 'completed', quantity: '3' }],
|
||||
|
||||
@@ -2,7 +2,7 @@ import { get, post, put, del, postForm, type RequestControlOptions } from '../re
|
||||
import {
|
||||
LoginResponse, AccountDetail, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType
|
||||
} from '../types';
|
||||
import { formatLocalDate } from '../dateRange';
|
||||
@@ -480,11 +480,21 @@ export const previewItemPublishBatch = async (form: {
|
||||
file: File;
|
||||
imagesZip?: File | null;
|
||||
defaultCookieId?: string;
|
||||
fallbackCategory: {
|
||||
catId: string;
|
||||
catName: string;
|
||||
channelCatId?: string;
|
||||
tbCatId?: string;
|
||||
};
|
||||
}): Promise<any> => {
|
||||
const body = new FormData();
|
||||
body.set('file', form.file);
|
||||
if (form.imagesZip) body.set('images_zip', form.imagesZip);
|
||||
if (form.defaultCookieId) body.set('default_cookie_id', form.defaultCookieId);
|
||||
body.set('fallback_category_id', form.fallbackCategory.catId);
|
||||
body.set('fallback_category_name', form.fallbackCategory.catName);
|
||||
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
|
||||
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
|
||||
return postForm('/items/publish-batches/preview', body);
|
||||
}
|
||||
|
||||
@@ -518,10 +528,7 @@ export const updateItem = async (cookieId: string, itemId: string, data: Partial
|
||||
}
|
||||
|
||||
// Rules - 自动化规则
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
const res = await get<any>('/automation-rules');
|
||||
const rules = Array.isArray(res) ? res : (res.data || res.rules || []);
|
||||
return rules.map((item: any) => ({
|
||||
const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map((item: any) => ({
|
||||
id: String(item.id),
|
||||
name: item.name || '',
|
||||
trigger_type: item.trigger_type || 'order_paid',
|
||||
@@ -565,6 +572,47 @@ export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
const res = await get<any>('/automation-rules');
|
||||
const rules = Array.isArray(res) ? res : (res.data || res.rules || []);
|
||||
return normalizeShippingRules(rules);
|
||||
}
|
||||
|
||||
export interface ShippingRuleListParams {
|
||||
cookieId?: string;
|
||||
triggerType?: AutomationTriggerType | '';
|
||||
enabled?: boolean;
|
||||
search?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export const getShippingRulesPage = async ({
|
||||
cookieId,
|
||||
triggerType,
|
||||
enabled,
|
||||
search,
|
||||
page = 1,
|
||||
pageSize = 10,
|
||||
}: ShippingRuleListParams = {}): Promise<PaginatedResponse<ShippingRule>> => {
|
||||
const res = await get<any>('/automation-rules', {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
cookie_id: cookieId || undefined,
|
||||
trigger_type: triggerType || undefined,
|
||||
enabled,
|
||||
search: search?.trim() || undefined,
|
||||
});
|
||||
const rules = normalizeShippingRules(Array.isArray(res) ? res : (res.data || res.rules || []));
|
||||
return {
|
||||
success: true,
|
||||
data: rules,
|
||||
total: Number(res.total ?? rules.length),
|
||||
page: Number(res.page ?? page),
|
||||
page_size: Number(res.page_size ?? pageSize),
|
||||
total_pages: Number(res.total_pages ?? (rules.length ? 1 : 0)),
|
||||
};
|
||||
}
|
||||
|
||||
const orderAutomationActions = (triggerType: string, actions: AutomationAction[]) => {
|
||||
|
||||
@@ -128,6 +128,17 @@ type AutomationRuleInput struct {
|
||||
Actions []AutomationActionInput
|
||||
}
|
||||
|
||||
// AutomationRuleListFilter 是自动化规则列表的筛选和分页条件。
|
||||
type AutomationRuleListFilter struct {
|
||||
UserID int64
|
||||
CookieID string
|
||||
TriggerType string
|
||||
Enabled *bool
|
||||
Search string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// AutomationActionInput 是创建动作的输入。
|
||||
type AutomationActionInput struct {
|
||||
ActionType string
|
||||
@@ -142,15 +153,59 @@ type AutomationActionInput struct {
|
||||
|
||||
// ListForUser 返回用户下全部自动化规则和动作。
|
||||
func (a *AutomationRules) ListForUser(ctx context.Context, userID int64) ([]AutomationRule, error) {
|
||||
rules, _, err := a.ListPageForUser(ctx, AutomationRuleListFilter{UserID: userID})
|
||||
return rules, err
|
||||
}
|
||||
|
||||
// ListPageForUser 按用户隔离筛选并分页查询自动化规则和动作。
|
||||
func (a *AutomationRules) ListPageForUser(ctx context.Context, f AutomationRuleListFilter) ([]AutomationRule, int, error) {
|
||||
where := []string{"r.user_id=?"}
|
||||
args := []any{f.UserID}
|
||||
if f.CookieID != "" {
|
||||
where = append(where, "r.cookie_id=?")
|
||||
args = append(args, f.CookieID)
|
||||
}
|
||||
if f.TriggerType != "" {
|
||||
where = append(where, "r.trigger_type=?")
|
||||
args = append(args, f.TriggerType)
|
||||
}
|
||||
if f.Enabled != nil {
|
||||
where = append(where, "r.enabled=?")
|
||||
args = append(args, boolToInt(*f.Enabled))
|
||||
}
|
||||
if search := strings.ToLower(strings.TrimSpace(f.Search)); search != "" {
|
||||
pattern := "%" + search + "%"
|
||||
where = append(where, `(LOWER(COALESCE(r.name,'')) LIKE ?
|
||||
OR LOWER(COALESCE(r.item_id,'')) LIKE ?
|
||||
OR LOWER(COALESCE(i.item_title,'')) LIKE ?)`)
|
||||
args = append(args, pattern, pattern, pattern)
|
||||
}
|
||||
whereSQL := strings.Join(where, " AND ")
|
||||
|
||||
var total int
|
||||
if err := a.DB.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*)
|
||||
FROM automation_rules r
|
||||
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
|
||||
WHERE `+whereSQL, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
queryArgs := append([]any{}, args...)
|
||||
limitSQL := ""
|
||||
if f.Limit > 0 {
|
||||
limitSQL = " LIMIT ? OFFSET ?"
|
||||
queryArgs = append(queryArgs, f.Limit, f.Offset)
|
||||
}
|
||||
rows, err := a.DB.QueryContext(ctx, `
|
||||
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
|
||||
r.priority,r.config_json,r.created_at,r.updated_at
|
||||
FROM automation_rules r
|
||||
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
|
||||
WHERE r.user_id=?
|
||||
ORDER BY r.created_at DESC,r.id DESC`, userID)
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY r.created_at DESC,r.id DESC`+limitSQL, queryArgs...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AutomationRule{}
|
||||
@@ -159,17 +214,17 @@ SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.t
|
||||
var enabled int
|
||||
if err := rows.Scan(&r.ID, &r.UserID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.Name, &r.TriggerType,
|
||||
&enabled, &r.Priority, &r.ConfigJSON, &r.CreatedAt, &r.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
return nil, 0, err
|
||||
}
|
||||
r.Enabled = enabled != 0
|
||||
acts, err := a.Actions(ctx, r.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, 0, err
|
||||
}
|
||||
r.Actions = acts
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
return out, total, rows.Err()
|
||||
}
|
||||
|
||||
// Match 查询某事件可触发的规则。商品级规则存在时只返回商品级规则;
|
||||
@@ -808,7 +863,11 @@ func (a *AutomationRules) MarkOrderEventTime(ctx context.Context, orderID, field
|
||||
default:
|
||||
return fmt.Errorf("不允许更新的订单时间字段: %s", field)
|
||||
}
|
||||
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=CASE WHEN COALESCE("+field+",'')='' THEN CURRENT_TIMESTAMP ELSE "+field+" END, updated_at=CURRENT_TIMESTAMP WHERE order_id=?", orderID)
|
||||
// 只在字段为空时写入当前时间,已有值则保留(幂等)。用 WHERE 过滤替代
|
||||
// CASE WHEN ... THEN CURRENT_TIMESTAMP ELSE field END:后者在 Postgres 上会
|
||||
// 因 THEN(timestamptz) 与 ELSE(text) 分支类型不可匹配而报 SQLSTATE 42804。
|
||||
// CURRENT_TIMESTAMP 直接赋值给 TEXT 列在三方言下均成立(见 IncrementReviewRequest)。
|
||||
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE order_id=? AND COALESCE("+field+",'')=''", orderID)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ type ItemPublishBatchRow struct {
|
||||
PostageMode string // 邮费模式:free/buyer/seller
|
||||
Postage string
|
||||
ImagesJSON string // 图片引用 JSON 数组(相对 UploadDir 的路径)
|
||||
CategoryJSON string // 自动识别失败时使用的指定类目 JSON
|
||||
AutomationJSON string // 发布后自动创建的自动化规则配置 JSON
|
||||
Status string // pending/running/success/failed
|
||||
ItemID string // 发布成功后回填的闲鱼商品 ID
|
||||
@@ -94,16 +95,19 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
if row.RawJSON == "" {
|
||||
row.RawJSON = "{}"
|
||||
}
|
||||
if row.CategoryJSON == "" {
|
||||
row.CategoryJSON = "{}"
|
||||
}
|
||||
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,automation_json,status,item_id,item_url,error_message,failure_kind,raw_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
images_json,category_json,automation_json,status,item_id,item_url,error_message,failure_kind,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, row.AutomationJSON,
|
||||
row.Quantity, row.PostageMode, row.Postage, row.ImagesJSON, row.CategoryJSON, row.AutomationJSON,
|
||||
row.Status, row.ItemID, row.ItemURL, row.ErrorMessage, row.FailureKind, row.RawJSON); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -189,7 +193,7 @@ func (b *ItemPublishBatches) Recoverable(ctx context.Context, now int64, limit i
|
||||
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,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
images_json,COALESCE(category_json,'{}'),COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
COALESCE(failure_kind,''),COALESCE(worker_token,''),
|
||||
raw_json,created_at,updated_at
|
||||
FROM item_publish_batch_rows WHERE batch_id=? ORDER BY row_no`, batchID)
|
||||
@@ -201,7 +205,7 @@ func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPu
|
||||
for rows.Next() {
|
||||
var r ItemPublishBatchRow
|
||||
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, &r.AutomationJSON,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.CategoryJSON, &r.AutomationJSON,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.FailureKind, &r.WorkerToken,
|
||||
&r.RawJSON, &r.CreatedAt,
|
||||
&r.UpdatedAt); err != nil {
|
||||
@@ -220,7 +224,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,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
images_json,COALESCE(category_json,'{}'),COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
COALESCE(failure_kind,''),COALESCE(worker_token,''),
|
||||
raw_json,created_at,updated_at
|
||||
FROM item_publish_batch_rows WHERE batch_id=? AND status IN `+statuses+` ORDER BY row_no`, batchID)
|
||||
@@ -232,7 +236,7 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
|
||||
for rows.Next() {
|
||||
var r ItemPublishBatchRow
|
||||
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, &r.AutomationJSON,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.CategoryJSON, &r.AutomationJSON,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.FailureKind, &r.WorkerToken,
|
||||
&r.RawJSON, &r.CreatedAt,
|
||||
&r.UpdatedAt); err != nil {
|
||||
|
||||
@@ -125,8 +125,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
t.Fatalf("goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
// 依次回滚 22 到 14,再整体升级。
|
||||
for i := 0; i < 9; i++ {
|
||||
// 依次回滚 23 到 14,再整体升级。
|
||||
for i := 0; i < 10; i++ {
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down migration #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -143,6 +143,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
if columnExists(t, d, "account_tokens", "cookie_fingerprint") {
|
||||
t.Fatal("account_tokens.cookie_fingerprint should be removed after migration 22 down")
|
||||
}
|
||||
if columnExists(t, d, "item_publish_batch_rows", "category_json") {
|
||||
t.Fatal("item_publish_batch_rows.category_json should be removed after migration 23 down")
|
||||
}
|
||||
|
||||
if err := goose.Up(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("up after down: %v", err)
|
||||
@@ -160,6 +163,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
{"default_reply_records", "status"},
|
||||
{"default_reply_records", "text_sent"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
{"item_publish_batch_rows", "category_json"},
|
||||
} {
|
||||
if !columnExists(t, d, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batch_rows ADD COLUMN category_json LONGTEXT NULL;
|
||||
UPDATE item_publish_batch_rows SET category_json='{}' WHERE category_json IS NULL;
|
||||
ALTER TABLE item_publish_batch_rows MODIFY COLUMN category_json LONGTEXT NOT NULL;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batch_rows DROP COLUMN category_json;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batch_rows ADD COLUMN category_json TEXT NOT NULL DEFAULT '{}';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batch_rows DROP COLUMN category_json;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batch_rows ADD COLUMN category_json TEXT NOT NULL DEFAULT '{}';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batch_rows DROP COLUMN category_json;
|
||||
@@ -641,7 +641,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
t.Fatalf("set goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
for i := 0; i < 9; i++ {
|
||||
for i := 0; i < 10; i++ {
|
||||
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration down #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -658,6 +658,9 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "account_tokens", "cookie_fingerprint") {
|
||||
t.Fatal("account_tokens.cookie_fingerprint should be removed after down")
|
||||
}
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "item_publish_batch_rows", "category_json") {
|
||||
t.Fatal("item_publish_batch_rows.category_json should be removed after down")
|
||||
}
|
||||
|
||||
if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration up after down: %v", err)
|
||||
@@ -677,6 +680,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
{"automation_runs", "action_cursor"},
|
||||
{"automation_runs", "action_started"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
{"item_publish_batch_rows", "category_json"},
|
||||
} {
|
||||
if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
@@ -724,6 +728,67 @@ func TestMultiDB_CardsCreateGet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_MarkOrderEventTime 验证订单事件时间标记跨三库一致。重点覆盖
|
||||
// Postgres 回归:CASE WHEN ... THEN CURRENT_TIMESTAMP ELSE field END 会因
|
||||
// THEN(timestamptz) 与 ELSE(text) 分支类型不可匹配而报 SQLSTATE 42804。
|
||||
// 语义:字段为空时写入当前时间,已有值时不得覆盖(幂等)。
|
||||
func TestMultiDB_MarkOrderEventTime(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
t.Run(tg.name, func(t *testing.T) {
|
||||
defer tg.cleanup()
|
||||
ctx := context.Background()
|
||||
s := tg.store
|
||||
|
||||
uid := tg.name + "_evt_user_" + fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
s.Users.Create(ctx, uid, uid+"@e.com", "pw")
|
||||
user, _ := s.Users.GetByUsername(ctx, uid)
|
||||
cid := tg.name + "_evt_cookie_" + fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
if err := s.Cookies.Save(ctx, cid, "cv", user.ID); err != nil {
|
||||
t.Fatalf("Save cookie: %v", err)
|
||||
}
|
||||
oid := tg.name + "_evt_order_" + fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
if err := s.Orders.Upsert(ctx, oid, OrderUpsertOpts{ItemID: "i1", BuyerID: "b1", CookieID: cid}); err != nil {
|
||||
t.Fatalf("Upsert: %v", err)
|
||||
}
|
||||
|
||||
// 白名单字段为空时全部写入当前时间。
|
||||
for _, f := range []string{"paid_at", "shipped_at", "completed_at", "buyer_reviewed_at", "last_review_request_at"} {
|
||||
if err := s.Automation.MarkOrderEventTime(ctx, oid, f); err != nil {
|
||||
t.Fatalf("MarkOrderEventTime(%s) on %s: %v", f, tg.name, err)
|
||||
}
|
||||
}
|
||||
got, err := s.Orders.Get(ctx, oid)
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if got.PaidAt == "" || got.ShippedAt == "" || got.CompletedAt == "" || got.BuyerReviewedAt == "" || got.LastReviewRequestAt == "" {
|
||||
t.Fatalf("event timestamps not set on %s: %#v", tg.name, got)
|
||||
}
|
||||
|
||||
// 已有值时不得覆盖。
|
||||
const original = "2020-01-02 03:04:05"
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE orders SET shipped_at=? WHERE order_id=?`, original, oid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.MarkOrderEventTime(ctx, oid, "shipped_at"); err != nil {
|
||||
t.Fatalf("MarkOrderEventTime(shipped_at) overwrite on %s: %v", tg.name, err)
|
||||
}
|
||||
var shippedAt string
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT shipped_at FROM orders WHERE order_id=?`, oid).Scan(&shippedAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if shippedAt != original {
|
||||
t.Fatalf("event timestamp overwritten on %s: %q want %q", tg.name, shippedAt, original)
|
||||
}
|
||||
|
||||
// 非法字段拒绝。
|
||||
if err := s.Automation.MarkOrderEventTime(ctx, oid, "order_status"); err == nil || !strings.Contains(err.Error(), "不允许") {
|
||||
t.Fatalf("非法字段应拒绝 on %s, got %v", tg.name, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func migrationTestSubdir(t *testing.T, dialect Dialect) (string, string) {
|
||||
t.Helper()
|
||||
switch dialect {
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestPublishBatches_CreateGetRows(t *testing.T) {
|
||||
t.Fatalf("Get 不存在应 ErrNotFound, got %v", err)
|
||||
}
|
||||
|
||||
// Rows 验证缺省值(quantity=1, postage_mode=free, status=pending, images_json=[], automation_json={})。
|
||||
// Rows 验证缺省值(quantity=1, postage_mode=free, status=pending, JSON 字段均已补齐)。
|
||||
gotRows, err := s.PublishBatches.Rows(ctx, "b1")
|
||||
if err != nil {
|
||||
t.Fatalf("Rows: %v", err)
|
||||
@@ -62,7 +62,7 @@ func TestPublishBatches_CreateGetRows(t *testing.T) {
|
||||
}
|
||||
r0 := gotRows[0]
|
||||
if r0.Quantity != 1 || r0.PostageMode != "free" || r0.Status != "pending" ||
|
||||
r0.ImagesJSON != "[]" || r0.AutomationJSON != "{}" || r0.RawJSON != "{}" {
|
||||
r0.ImagesJSON != "[]" || r0.CategoryJSON != "{}" || r0.AutomationJSON != "{}" || r0.RawJSON != "{}" {
|
||||
t.Fatalf("缺省值: %#v", r0)
|
||||
}
|
||||
if gotRows[1].Quantity != 5 || gotRows[1].PostageMode != "buyer" {
|
||||
|
||||
@@ -76,6 +76,61 @@ func TestAutomationRulesCRUD(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','item-blue','蓝色会员')`)
|
||||
for _, input := range []db.AutomationRuleInput{
|
||||
{UserID: 1, CookieID: "acc1", ItemID: "item-blue", Name: "付款规则", TriggerType: automation.TriggerOrderPaid, Enabled: true, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionConfirmShipment, Enabled: true}}},
|
||||
{UserID: 1, CookieID: "acc1", Name: "评价赠品", TriggerType: automation.TriggerBuyerReviewed, Enabled: false, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "gift", Enabled: true}}},
|
||||
{UserID: 1, CookieID: "acc1", Name: "求评价", TriggerType: automation.TriggerReviewMissingTimeout, Enabled: true, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "review", Enabled: true}}},
|
||||
} {
|
||||
if _, err := store.Automation.Create(ctx, input); err != nil {
|
||||
t.Fatalf("create rule: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
request := func(path string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
var body map[string]any
|
||||
if rec.Code == http.StatusOK {
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
}
|
||||
return rec.Code, body
|
||||
}
|
||||
|
||||
status, filtered := request("/automation-rules?page=1&page_size=10&cookie_id=acc1&trigger_type=order_paid&enabled=true&search=%E8%93%9D%E8%89%B2")
|
||||
if status != http.StatusOK || filtered["total"] != float64(1) || filtered["total_pages"] != float64(1) {
|
||||
t.Fatalf("filtered status=%d body=%+v", status, filtered)
|
||||
}
|
||||
data, ok := filtered["data"].([]any)
|
||||
if !ok || len(data) != 1 || data[0].(map[string]any)["name"] != "付款规则" {
|
||||
t.Fatalf("filtered data=%+v", filtered["data"])
|
||||
}
|
||||
|
||||
status, lastPage := request("/automation-rules?page=99&page_size=1")
|
||||
if status != http.StatusOK || lastPage["total"] != float64(3) || lastPage["page"] != float64(3) {
|
||||
t.Fatalf("last page status=%d body=%+v", status, lastPage)
|
||||
}
|
||||
if data, ok := lastPage["data"].([]any); !ok || len(data) != 1 {
|
||||
t.Fatalf("last page data=%+v", lastPage["data"])
|
||||
}
|
||||
|
||||
status, _ = request("/automation-rules?page=1&enabled=maybe")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("invalid enabled status=%d", status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleBadTriggerType 不支持的触发类型 400。
|
||||
func TestAutomationRuleBadTriggerType(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
|
||||
@@ -104,11 +104,82 @@ type automationRuleRequest struct {
|
||||
|
||||
func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
rules, err := s.Store.Automation.ListForUser(r.Context(), sess.UserID)
|
||||
query := r.URL.Query()
|
||||
_, paginated := query["page"]
|
||||
if !paginated {
|
||||
rules, err := s.Store.Automation.ListForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, automationRulesJSON(rules))
|
||||
return
|
||||
}
|
||||
|
||||
page := atoiDefault(query.Get("page"), 1)
|
||||
pageSize := atoiDefault(query.Get("page_size"), 10)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 10
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
cookieID := strings.TrimSpace(query.Get("cookie_id"))
|
||||
if cookieID != "" {
|
||||
if _, ok := s.cookieForUser(r, sess.UserID, cookieID); !ok {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
}
|
||||
triggerType := strings.TrimSpace(query.Get("trigger_type"))
|
||||
if triggerType != "" {
|
||||
switch triggerType {
|
||||
case automation.TriggerOrderPaid, automation.TriggerBuyerReviewed, automation.TriggerReviewMissingTimeout:
|
||||
default:
|
||||
writeErr(w, http.StatusBadRequest, "不支持的触发类型")
|
||||
return
|
||||
}
|
||||
}
|
||||
var enabled *bool
|
||||
if rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" {
|
||||
value, parseErr := strconv.ParseBool(rawEnabled)
|
||||
if parseErr != nil {
|
||||
writeErr(w, http.StatusBadRequest, "启用状态必须是 true 或 false")
|
||||
return
|
||||
}
|
||||
enabled = &value
|
||||
}
|
||||
|
||||
rules, total, err := s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{
|
||||
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
|
||||
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
|
||||
return
|
||||
}
|
||||
totalPages := (total + pageSize - 1) / pageSize
|
||||
if totalPages > 0 && page > totalPages {
|
||||
page = totalPages
|
||||
rules, _, err = s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{
|
||||
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
|
||||
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true, "data": automationRulesJSON(rules), "total": total,
|
||||
"page": page, "page_size": pageSize, "total_pages": totalPages,
|
||||
})
|
||||
}
|
||||
|
||||
func automationRulesJSON(rules []db.AutomationRule) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
actions := make([]map[string]any, 0, len(rule.Actions))
|
||||
@@ -127,7 +198,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
|
||||
"created_at": rule.CreatedAt, "updated_at": rule.UpdatedAt,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -47,6 +47,7 @@ type publishBatchPreviewRow struct {
|
||||
Price string `json:"price"`
|
||||
Quantity int `json:"quantity"`
|
||||
Images []string `json:"images"`
|
||||
Category mtop.PublishCategory `json:"category"`
|
||||
Automation publishAutomationConfig `json:"automation"`
|
||||
}
|
||||
|
||||
@@ -61,6 +62,7 @@ type publishBatchParsedRow struct {
|
||||
PostageMode string
|
||||
Postage string
|
||||
Images []string
|
||||
Category mtop.PublishCategory
|
||||
Automation publishAutomationConfig
|
||||
Errors []string
|
||||
Raw map[string]any
|
||||
@@ -111,6 +113,16 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusForbidden, "默认账号不属于当前用户")
|
||||
return
|
||||
}
|
||||
fallbackCategory := mtop.PublishCategory{
|
||||
CatID: strings.TrimSpace(r.FormValue("fallback_category_id")),
|
||||
CatName: strings.TrimSpace(r.FormValue("fallback_category_name")),
|
||||
ChannelCatID: strings.TrimSpace(r.FormValue("fallback_channel_category_id")),
|
||||
TBCatID: strings.TrimSpace(r.FormValue("fallback_tb_category_id")),
|
||||
}
|
||||
if fallbackCategory.CatID == "" || fallbackCategory.CatName == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请同时填写批次兜底类目 ID 和类目名称")
|
||||
return
|
||||
}
|
||||
source, sourceHeader, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "缺少商品表格文件")
|
||||
@@ -181,7 +193,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusBadRequest, fmt.Sprintf("单个批次最多支持 %d 条商品", maxPublishBatchRows))
|
||||
return
|
||||
}
|
||||
parsed := s.parsePublishRows(r.Context(), sess.UserID, defaultCookieID, uploadDir, maps)
|
||||
parsed := s.parsePublishRows(r.Context(), sess.UserID, defaultCookieID, uploadDir, fallbackCategory, maps)
|
||||
rows := make([]db.ItemPublishBatchRow, 0, len(parsed))
|
||||
previewRows := make([]publishBatchPreviewRow, 0, len(parsed))
|
||||
valid, invalid := 0, 0
|
||||
@@ -193,6 +205,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
invalid++
|
||||
}
|
||||
imagesJSON, _ := json.Marshal(p.Images)
|
||||
categoryJSON, _ := json.Marshal(p.Category)
|
||||
automationJSON, _ := json.Marshal(p.Automation)
|
||||
rawJSON, _ := json.Marshal(p.Raw)
|
||||
status := "pending"
|
||||
@@ -212,6 +225,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
PostageMode: p.PostageMode,
|
||||
Postage: p.Postage,
|
||||
ImagesJSON: string(imagesJSON),
|
||||
CategoryJSON: string(categoryJSON),
|
||||
AutomationJSON: string(automationJSON),
|
||||
Status: status,
|
||||
ErrorMessage: errMsg,
|
||||
@@ -227,6 +241,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
Price: p.Price,
|
||||
Quantity: p.Quantity,
|
||||
Images: p.Images,
|
||||
Category: p.Category,
|
||||
Automation: p.Automation,
|
||||
})
|
||||
}
|
||||
@@ -469,10 +484,7 @@ func (s *Server) recoverPublishBatchesOnce(ctx context.Context) {
|
||||
}
|
||||
for _, batch := range batches {
|
||||
if batch.Status == "canceling" {
|
||||
finalized, finalizeErr := s.Store.PublishBatches.FinalizeExpiredCancellation(ctx, batch.ID, time.Now().UTC().Unix())
|
||||
if finalizeErr != nil || !finalized {
|
||||
continue
|
||||
}
|
||||
_, _ = s.Store.PublishBatches.FinalizeExpiredCancellation(ctx, batch.ID, time.Now().UTC().Unix())
|
||||
continue
|
||||
}
|
||||
workerToken := randomHex(16)
|
||||
@@ -524,11 +536,14 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("\xEF\xBB\xBF")
|
||||
cw := csv.NewWriter(&buf)
|
||||
_ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "商品ID", "商品URL", "错误原因"})
|
||||
_ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "兜底类目ID", "兜底类目名称", "商品ID", "商品URL", "错误原因"})
|
||||
for _, row := range rows {
|
||||
var category mtop.PublishCategory
|
||||
_ = json.Unmarshal([]byte(row.CategoryJSON), &category)
|
||||
_ = cw.Write([]string{
|
||||
strconv.Itoa(row.RowNo), safeCSVCell(row.Status), safeCSVCell(row.CookieID), safeCSVCell(row.Title), safeCSVCell(row.Price),
|
||||
strconv.Itoa(row.Quantity), safeCSVCell(row.ItemID), safeCSVCell(row.ItemURL), safeCSVCell(row.ErrorMessage),
|
||||
strconv.Itoa(row.Quantity), safeCSVCell(category.CatID), safeCSVCell(category.CatName),
|
||||
safeCSVCell(row.ItemID), safeCSVCell(row.ItemURL), safeCSVCell(row.ErrorMessage),
|
||||
})
|
||||
}
|
||||
cw.Flush()
|
||||
@@ -700,10 +715,7 @@ func (s *Server) finishInterruptedPublishBatch(ctx context.Context, userID int64
|
||||
if batch.WorkerToken != workerToken {
|
||||
return
|
||||
}
|
||||
finalized, finalizeErr := s.Store.PublishBatches.FinalizeCanceled(wctx, batchID, workerToken)
|
||||
if finalizeErr != nil || !finalized {
|
||||
return
|
||||
}
|
||||
_, _ = s.Store.PublishBatches.FinalizeCanceled(wctx, batchID, workerToken)
|
||||
}
|
||||
// 取消产生的 interrupted 失败行允许用户稍后重试,图片由统一的过期清理保留 7 天。
|
||||
return
|
||||
@@ -722,10 +734,7 @@ func (s *Server) finishPublishBatch(ctx context.Context, userID int64, batchID,
|
||||
return
|
||||
}
|
||||
if batch.Status == "canceling" {
|
||||
finalized, finalizeErr := s.Store.PublishBatches.FinalizeCanceled(wctx, batchID, workerToken)
|
||||
if finalizeErr != nil || !finalized {
|
||||
return
|
||||
}
|
||||
_, _ = s.Store.PublishBatches.FinalizeCanceled(wctx, batchID, workerToken)
|
||||
// 取消任务仍可“重试失败项”,不能在此删除重试所需的本地图片。
|
||||
return
|
||||
}
|
||||
@@ -772,6 +781,17 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
res := &mtop.PublishItemResult{ItemID: row.ItemID, ItemURL: row.ItemURL, Title: row.Title, PriceText: row.Price, Quantity: row.Quantity}
|
||||
var responseCookieErr error
|
||||
if row.ItemID == "" {
|
||||
rawCategory := strings.TrimSpace(row.CategoryJSON)
|
||||
if rawCategory == "" || rawCategory == "{}" {
|
||||
return errors.New("批量任务缺少兜底类目,请重新上传并创建任务")
|
||||
}
|
||||
var fallbackCategory mtop.PublishCategory
|
||||
if err := json.Unmarshal([]byte(rawCategory), &fallbackCategory); err != nil {
|
||||
return errors.New("兜底类目配置损坏,请重新创建批量任务")
|
||||
}
|
||||
if strings.TrimSpace(fallbackCategory.CatID) == "" || strings.TrimSpace(fallbackCategory.CatName) == "" {
|
||||
return errors.New("兜底类目缺少类目 ID 或类目名称,请重新创建批量任务")
|
||||
}
|
||||
images, err := loadBatchPublishImages(ctx, batch.UploadDir, row)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -810,6 +830,7 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
PostageMode: row.PostageMode,
|
||||
PostageCents: postageCents,
|
||||
Virtual: true,
|
||||
FallbackCategory: &fallbackCategory,
|
||||
Images: images,
|
||||
})
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
@@ -856,6 +877,9 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
}
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, mtop.ErrPublishCategoryUnrecognized) {
|
||||
return err
|
||||
}
|
||||
return &uncertainRemotePublishError{err: fmt.Errorf("远端发布调用失败且结果未知: %w", err)}
|
||||
}
|
||||
rawJSON, _ := json.Marshal(res.RawData)
|
||||
@@ -1000,7 +1024,7 @@ func (s *Server) ensurePublishAutomationRule(ctx context.Context, input db.Autom
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCookieID, uploadDir string, input []map[string]any) []publishBatchParsedRow {
|
||||
func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCookieID, uploadDir string, fallbackCategory mtop.PublishCategory, input []map[string]any) []publishBatchParsedRow {
|
||||
out := make([]publishBatchParsedRow, 0, len(input))
|
||||
for i, m := range input {
|
||||
row := publishBatchParsedRow{
|
||||
@@ -1031,6 +1055,21 @@ func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCook
|
||||
row.PostageMode = "fixed"
|
||||
}
|
||||
row.Quantity = atoiPublishDefault(firstImportString(m, "quantity", "库存", "数量"), 1)
|
||||
rowCategory := mtop.PublishCategory{
|
||||
CatID: firstImportString(m, "category_id", "类目ID", "商品类目ID"),
|
||||
CatName: firstImportString(m, "category_name", "类目名称", "商品类目名称", "类目"),
|
||||
ChannelCatID: firstImportString(m, "channel_category_id", "频道类目ID"),
|
||||
TBCatID: firstImportString(m, "tb_category_id", "淘宝类目ID"),
|
||||
}
|
||||
hasRowCategory := rowCategory.CatID != "" || rowCategory.CatName != "" || rowCategory.ChannelCatID != "" || rowCategory.TBCatID != ""
|
||||
if hasRowCategory {
|
||||
row.Category = rowCategory
|
||||
if rowCategory.CatID == "" || rowCategory.CatName == "" {
|
||||
row.Errors = append(row.Errors, "指定行类目时必须同时填写类目ID和类目名称")
|
||||
}
|
||||
} else {
|
||||
row.Category = fallbackCategory
|
||||
}
|
||||
row.Automation = parsePublishAutomation(m)
|
||||
row.Images = splitImageRefs(firstImportString(m, "images", "image", "图片", "商品图片"))
|
||||
if row.CookieID == "" {
|
||||
@@ -1194,11 +1233,14 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow
|
||||
}
|
||||
var refs []string
|
||||
_ = json.Unmarshal([]byte(row.ImagesJSON), &refs)
|
||||
var category mtop.PublishCategory
|
||||
_ = json.Unmarshal([]byte(row.CategoryJSON), &category)
|
||||
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,
|
||||
"category": category,
|
||||
"automation": automationCfg,
|
||||
"status": row.Status, "item_id": row.ItemID, "item_url": row.ItemURL,
|
||||
"error_message": row.ErrorMessage, "failure_kind": row.FailureKind,
|
||||
|
||||
@@ -181,6 +181,14 @@ func normalizePublishHeader(header string) string {
|
||||
return "postage"
|
||||
case "images", "image", "图片", "商品图片":
|
||||
return "images"
|
||||
case "categoryid", "catid", "类目id", "商品类目id":
|
||||
return "category_id"
|
||||
case "categoryname", "catname", "类目名称", "商品类目名称", "类目":
|
||||
return "category_name"
|
||||
case "channelcategoryid", "channelcatid", "频道类目id":
|
||||
return "channel_category_id"
|
||||
case "tbcategoryid", "tbcatid", "淘宝类目id":
|
||||
return "tb_category_id"
|
||||
case "paiddeliveryenabled", "付款发货启用", "付款后自动发货":
|
||||
return "paid_delivery_enabled"
|
||||
case "paiddeliverycontents", "付款发货内容", "付款后发送的卡密":
|
||||
|
||||
@@ -279,6 +279,21 @@ func TestParsePublishCardActions(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizePublishHeaderCategoryFallbackLabels(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"类目ID": "category_id",
|
||||
"类目名称": "category_name",
|
||||
"频道类目ID": "channel_category_id",
|
||||
"淘宝类目ID": "tb_category_id",
|
||||
"category_id": "category_id",
|
||||
}
|
||||
for input, want := range cases {
|
||||
if got := normalizePublishHeader(input); got != want {
|
||||
t.Fatalf("normalizePublishHeader(%q)=%q want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePublishAutomationSupportsMultipleCards(t *testing.T) {
|
||||
cfg := parsePublishAutomation(map[string]any{
|
||||
"paid_delivery_enabled": "是",
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -94,6 +95,8 @@ func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) stri
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -121,6 +124,8 @@ func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\nacc1,商品B,13.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -296,6 +301,7 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
|
||||
func TestRunItemPublishBatch_Success(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
var publishedCategory map[string]any
|
||||
// 所有 mtop 调用返回 SUCCESS;发布调用返回 itemId。
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
u := req.URL.String()
|
||||
@@ -306,9 +312,14 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
|
||||
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"100","catName":"数码"}}}`
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{}}`
|
||||
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","url":"https://x/item/123456","picUrl":"https://img.alicdn.com/published.png","categoryId":"100","categoryName":"数码","title":"商品A","priceText":"12.50","quantity":"5"}}`
|
||||
rawBody, _ := io.ReadAll(req.Body)
|
||||
form, _ := url.ParseQuery(string(rawBody))
|
||||
var publishData map[string]any
|
||||
_ = json.Unmarshal([]byte(form.Get("data")), &publishData)
|
||||
publishedCategory, _ = publishData["itemCatDTO"].(map[string]any)
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","url":"https://x/item/123456","picUrl":"https://img.alicdn.com/published.png","categoryId":"5001","categoryName":"虚拟商品","title":"商品A","priceText":"12.50","quantity":"5"}}`
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
@@ -376,6 +387,9 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
|
||||
if row["status"] != "success" || row["item_id"] == "" {
|
||||
t.Fatalf("row should be success with item_id: %+v", row)
|
||||
}
|
||||
if publishedCategory["catId"] != "5001" || publishedCategory["catName"] != "虚拟商品" {
|
||||
t.Fatalf("batch did not apply fallback category: %+v", publishedCategory)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *testing.T) {
|
||||
|
||||
@@ -79,6 +79,8 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -98,6 +100,64 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
if res["success"] != true || res["valid"] != float64(1) {
|
||||
t.Fatalf("预检异常: %+v", res)
|
||||
}
|
||||
previewRow := res["rows"].([]any)[0].(map[string]any)
|
||||
category := previewRow["category"].(map[string]any)
|
||||
if category["cat_id"] != "5001" || category["cat_name"] != "虚拟商品" {
|
||||
t.Fatalf("预检未保存兜底类目: %+v", category)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewItemPublishBatchRequiresFallbackCategory(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
file, _ := mw.CreateFormFile("file", "products.csv")
|
||||
file.Write([]byte("标题,价格,图片\n商品A,12.50,https://example.com/a.png\n"))
|
||||
_ = mw.Close()
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "兜底类目") {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewItemPublishBatchRowCategoryOverridesFallback(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "批次类目")
|
||||
file, _ := mw.CreateFormFile("file", "products.csv")
|
||||
file.Write([]byte("标题,价格,图片,类目ID,类目名称\n商品A,12.50,https://example.com/a.png,7001,行指定类目\n"))
|
||||
_ = mw.Close()
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
row := res["rows"].([]any)[0].(map[string]any)
|
||||
category := row["category"].(map[string]any)
|
||||
if category["cat_id"] != "7001" || category["cat_name"] != "行指定类目" {
|
||||
t.Fatalf("row category=%+v", category)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchNoFile 缺表格文件 400。
|
||||
@@ -110,6 +170,8 @@ func TestPreviewItemPublishBatchNoFile(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
@@ -181,6 +243,9 @@ func TestPreviewItemPublishBatchTooManyRows(t *testing.T) {
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write(csvBuf.Bytes())
|
||||
_ = mw.Close()
|
||||
@@ -211,6 +276,8 @@ func TestPreviewItemPublishBatchZipTraversal(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,../escape.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{positiLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-inset-1{top:-.25rem;right:-.25rem;bottom:-.25remLine truncated
|
||||
@@ -1,19 +0,0 @@
|
||||
import{j as e,r as n,b as ke,c as ua,d as pa}from"./react-vendor-DZnRGM0-.js";import{L as ha,U as Ot,S as qt,C as Vs,B as Bt,Z as Gs,a as ms,b as Hs,c as zt,d as ga,e as ns,A as xt,D as ba,f as mt,P as Ut,g as Ns,E as Wt,T as fa,h as ya,i as Le,Q as Ts,j as is,k as Ze,l as xs,m as ut,R as Ue,n as Vt,o as ja,p as ze,X as we,K as Na,q as rs,r as ss,s as He,t as Xe,u as pt,v as Gt,w as us,x as va,y as _a,z as js,F as wa,G as ka,H as ht,I as gt,J as Ca,M as Sa,N as La,O as Aa,V as Fs,W as ws,Y as Jt,_ as Ia,$ as $a,a0 as Js,a1 as Ra,a2 as Pa,a3 as Qs,a4 as bt,a5 as Ea,a6 as As,a7 as Qt,a8 as Da,a9 as Ta,aa as et,ab as Kt,ac as Fa,ad as Ma}from"./icons-vendor-RenKjhri.js";import{R as ks,B as Oa,X as ft,Y as yt,T as Ms,a as qa,C as Os,A as Ba,b as za,c as Ua,P as jt,d as Nt,L as Wa}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const h of document.querySelectorAll('link[rel="modulepreload"]'))c(h);new MutationObserver(h=>{for(const f of h)if(f.type==="childList")for(const S of f.addedNodes)S.tagName==="LINK"&&S.rel==="modulepreload"&&c(S)}).observe(document,{childList:!0,subtree:!0});function l(h){const f={};return h.integrity&&(f.integrity=h.integrity),h.referrerPolicy&&(f.referrerPolicy=h.referrerPolicy),h.crossOrigin==="use-credentials"?f.credentials="include":h.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function c(h){if(h.ep)return;h.ep=!0;const f=l(h);fetch(h.href,f)}})();const Va=({className:s="w-full h-full text-white"})=>e.jsx("svg",{className:s,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),Ks=({sizeClass:s="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${s} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Hs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:rt,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:w,children:"取消"}),e.jsxs("button",{onClick:_e,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:w,children:[w?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),w?"保存中...":"保存"]})]})})]})}),document.body)]})},yr=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),jr=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],It=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},Nr=()=>{const[s,t]=n.useState([]),[l,c]=n.useState([]),[h,f]=n.useState([]),[S,F]=n.useState({}),[p,I]=n.useState("all"),[y,W]=n.useState(""),[se,oe]=n.useState(""),[de,C]=n.useState(""),M=n.useRef(0),[ce,Y]=n.useState(1),[K,q]=n.useState(1),[xe,ue]=n.useState(!1),[N,P]=n.useState(!1),[O,G]=n.useState(!1),[ae,A]=n.useState(!1),[L,b]=n.useState(null),[v,B]=n.useState(null),[D,J]=n.useState({}),[Z,x]=n.useState(!1),[g,T]=n.useState(""),[R,X]=n.useState(!1),[le,U]=n.useState(null),[pe,j]=n.useState(null),[i,E]=n.useState(null),[d,w]=n.useState(!1),[H,Q]=n.useState(null),[re,Ne]=n.useState(null),ee=async()=>{const m=++M.current;ue(!0);try{const $=await bl(y||void 0,p,ce,20,de);if(m!==M.current)return;t($.data),q($.total_pages)}catch($){console.error("加载订单失败:",$)}finally{m===M.current&&ue(!1)}},ye=(m,$,me)=>{if(me&&me.trim())return me;if(S[`${m}:${$}`])return S[`${m}:${$}`];const je=l.find(Je=>{if(me&&Je.item_title){const r=me.toLowerCase(),a=Je.item_title.toLowerCase();return a.includes(r)||r.includes(a)}return!1});return je!=null&&je.item_title?je.item_title:"未知商品"},Ie=m=>{const $={};m.forEach(me=>{me.item_id&&($[`${me.cookie_id}:${me.item_id}`]=me.item_title||me.item_id)}),F($)};n.useEffect(()=>{const m=window.setTimeout(()=>{Y(1),C(se.trim())},300);return()=>window.clearTimeout(m)},[se]),n.useEffect(()=>{ee()},[y,p,ce,de]),n.useEffect(()=>{Promise.all([Ps(),ps()]).then(([m,$])=>{f(m),c($),Ie($)}).catch(m=>{console.error("加载商品列表失败:",m)})},[]);const he=n.useMemo(()=>new Map(h.map(m=>[m.id,m])),[h]),$e=m=>{const $=he.get(m),me=($==null?void 0:$.remark)||($==null?void 0:$.nickname);return me?`${me} · ${m.slice(0,6)}`:`账号 ${m.slice(0,8)}`},Te=m=>{const $=he.get(m);return($==null?void 0:$.remark)||($==null?void 0:$.nickname)||"未命名账号"},We=async()=>{ue(!0);try{const m=await jl(y||void 0,p);await ee(),m!=null&&m.message&&alert(m.message)}catch(m){console.error("同步订单失败:",m),alert((m==null?void 0:m.message)||"同步失败,请重试")}finally{ue(!1)}},Oe=m=>{T(m),U(null),x(!0)},Re=async m=>{var $;X(!0),U(null);try{const me=await vl([g],m),je=($=me==null?void 0:me.results)==null?void 0:$[0];je!=null&&je.success?(U({success:!0,message:je.message}),ee()):U({success:!1,message:(je==null?void 0:je.message)||"发货失败"})}catch(me){U({success:!1,message:(me==null?void 0:me.message)||"请求失败"})}finally{X(!1)}},Fe=m=>{b(m),P(!0)},qe=m=>{B({...m}),G(!0)},Pe=async()=>{if(!(!v||!v.order_id))try{const m={};v.status!==void 0&&(m.order_status=v.status),v.buyer_id!==void 0&&(m.buyer_id=v.buyer_id),v.amount!==void 0&&(m.amount=v.amount),v.receiver_name!==void 0&&(m.receiver_name=v.receiver_name),v.receiver_phone!==void
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(re=>re.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),w=new Blob(["\uFEFF"+d],{type:"text/csv;charset=utf-8"}),H=URL.createObjectURL(w),Q=document.createElement("a");Q.href=H,Q.download="卡密组批量导入模板.csv",document.body.appendChild(Q),Q.click(),Q.remove(),URL.revokeObjectURL(H)},U=async()=>{if(M){xe(!0),K(null);try{const i=await Al(M);if(K(i),i.created>0){const E=await Ye();t(E)}}catch(i){K({error:(i==null?void 0:i.message)||"上传失败"})}finally{xe(!1)}}},pe=async()=>{if(!(!ue||!P.trim())){xe(!0),ae(null);try{const i=await Il(ue,P);ae({added:i.added}),O("");const E=await Ye();t(E)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{xe(!1)}}},j=()=>{var i;C("create"),ce(null),K(null),N((i=R[0])!=null&&i.id?String(R[0].id):""),O(""),ae(null),oe(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:j,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(js,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>f(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Xe,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(wa,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:A,onChange:i=>L(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(Gt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:b,onChange:i=>v(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",X.length," / ",s.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:X.map(i=>{let E="";return i.type==="data"&&i.data_content?E=`库存: ${i.data_content.split(`
|
||||
`).filter(w=>w.trim()).length} 条`:i.type==="text"&&i.text_content?E=i.text_content:i.type==="api"&&i.api_config?E=i.api_config.url:i.type==="image"&&i.image_url&&(E="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(B,{type:i.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:i.name,children:i.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>T(i.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:i.id}),e.jsx(ka,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:E,children:E})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>g(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>D(i),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Z(i.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(ze,{className:"h-4 w-4"})})]})})]},i.id)})})]})}),X.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Ut,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:s.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&S&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>c(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:p.name||"",onChange:i=>I({...p,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:p.type||"text",onChange:i=>I({...p,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(S==null?void 0:S.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),p.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:p.api_url||"",onChange:i=>I({...p,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("Line truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:p.data_content?p.data_content.split(`
|
||||
`).filter(i=>i.trim()).length:0})," 条"]})]})]}),p.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:p.image_url||"",onChange:i=>I({...p,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),p.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:p.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:p.delay_seconds||0,onChange:i=>I({...p,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:p.description||"",onChange:i=>I({...p,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>I({...p,enabled:!p.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${p.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${p.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>c(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:J,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),h&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>f(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:y.name,onChange:i=>W({...y,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>W({...y,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Vs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>W({...y,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ht,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>W({...y,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),y.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:y.content.split(`
|
||||
`).filter(i=>i.trim()).length})," 条"]})]}),y.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:y.api_method,onChange:i=>W({...y,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:y.api_timeout,onChange:i=>W({...y,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:y.api_headers,onChange:i=>W({...y,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:y.api_params,onChange:i=>W({...y,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:y.description,onChange:i=>W({...y,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:y.delay_seconds,onChange:i=>W({...y,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>f(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:x,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),se&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>oe(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>C("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${de==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ca,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>C("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${de==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(js,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),de==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:le,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 tex
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),G&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",G.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>oe(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),de==="create"?e.jsxs("button",{onClick:U,disabled:!M||q,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[q?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(js,{className:"w-4 h-4"}),q?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:pe,disabled:!ue||!P.trim()||q||R.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[q?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Xe,{className:"w-4 h-4"}),q?"处理中...":"追加卡密"]})]})]})}),document.body)]})},wr=s=>s.find(t=>t.status==="running"||t.status==="canceling"),kr=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},Cr=({onConfigureDelivery:s})=>{const[t,l]=n.useState([]),[c,h]=n.useState([]),[f,S]=n.useState([]),[F,p]=n.useState(""),[I,y]=n.useState(""),[W,se]=n.useState(!1),[oe,de]=n.useState(!1),[C,M]=n.useState(!1),[ce,Y]=n.useState(!1),[K,q]=n.useState(!1),[xe,ue]=n.useState(!1),[N,P]=n.useState(!1),[O,G]=n.useState("upload"),[ae,A]=n.useState(null),[L,b]=n.useState(null),[v,B]=n.useState(null),[D,J]=n.useState(null),[Z,x]=n.useState(null),g=n.useRef(!1),[T,R]=n.useState(null),[X,le]=n.useState({}),[U,pe]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[j,i]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[E,d]=n.useState([]);n.useEffect(()=>{if(!xe||j.images.length===0){d([]);return}const r=j.images.map((a,u)=>({key:a.name+u,url:URL.createObjectURL(a)}));return d(r),()=>{r.forEach(a=>URL.revokeObjectURL(a.url))}},[xe,j.images]);const w=async()=>{const r=await ps();l(r)},H=async()=>{h(await $s())};n.useEffect(()=>{Promise.all([Ps(),ps(),$s(),kt(20)]).then(([r,a,u,k])=>{S(r),l(a),h(u);const V=k.find(te=>["running","canceling"].includes(te.status))||k.find(te=>te.status!=="preview");x(V||null)}).catch(r=>console.error("加载商品配置失败:",r))},[]),n.useEffect(()=>{if(!N||!(D!=null&&D.id)||!["running","canceling"].includes(D.status))return;const r=window.setInterval(async()=>{if(!g.current){g.current=!0;try{const a=await cs(D.id);J(a),x(a),["running","canceling"].includes(a.status)||(G("done"),await w(),await H())}catch(a){console.error("刷新批量铺货进度失败:",a)}finally{g.current=!1}}},3e3);return()=>{window.clearInterval(r)}},[N,D==null?void 0:D.id,D==null?void 0:D.status]);const Q=async()=>{if(!F)return alert("请先选择账号");se(!0);try{const r=await $l(F);await w(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{se(!1)}},re=r=>{R(r),le({...r}),Y(!0)},Ne=async()=>{if(T)try{await ql(T.cookie_id,T.item_id,{item_title:X.item_title||"",item_description:X.item_description||"",item_category:X.item_category||"",item_price:X.item_price||"",item_detail:X.item_detail||T.item_detail||""}),await w(),await H(),Y(!1),R(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},ee=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await Rl(r.cookie_id,r.item_id),l(a=>a.filter(u=>!(u.cookie_id===r.cookie_id&&u.item_id===r.item_id)))}catch(a){console.error("删除商品失败:",a),alert("删除失败,请重试")}},ye=async()=>{try{if(!U.cookie_id||!U.item_id){alert("请选择账号并填写商品ID");return}await Pl(U.cookie_id,{item_id:U.item_id,item_title:U.item_title,item_price:U.item_price,item_detail:U.item_image?JSON.stringify({item_image:U.item_image}):""}),await w(),q(!1),pe({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},Ie=async()=>{if(!j.cookie_id)return alert("请选择发布账号");if(!j.title.trim())return alert("请填写商品标题");if(!j.price.trim())return alert("请填写商品价格");if(!j.quantity||Number(j.quantity)<=0)return alert("库存数量必须大于 0");if(j.images.length===0)return alert("至少上传 1 张商品图片");if(j.postage_mode==="fixed"&&!j.postage.trim())return alert("请填写一口价邮费");de(!0);try{const r=await El(j);if(await w(),ue(!1),i({cookie_id:F||"",title:
Line truncated
|
||||
`),k=new Blob(["\uFEFF"+u],{type:"text/csv;charset=utf-8"}),V=URL.createObjectURL(k),te=document.createElement("a");te.href=V,te.download="批量铺货模板.csv",document.body.appendChild(te),te.click(),te.remove(),URL.revokeObjectURL(V)},Ve=()=>{pe(r=>({...r,cookie_id:F||r.cookie_id})),q(!0)},Ae=()=>{i(r=>({...r,cookie_id:F||r.cookie_id})),ue(!0)},Ge=r=>c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id).length>0?c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id):c.filter(a=>a.cookie_id===r.cookie_id&&!a.item_id),es=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},m=r=>{switch(r){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},$=n.useMemo(()=>new Map(f.map(r=>[r.id,r])),[f]),me=n.useMemo(()=>I?t.filter(r=>r.cookie_id===I):t,[I,t]),je=r=>{const a=$.get(r),u=(a==null?void 0:a.remark)||(a==null?void 0:a.nickname);return u?`${u} · ${r.slice(0,6)}`:`账号 ${r.slice(0,8)}`},Je=r=>{const a=$.get(r);return(a==null?void 0:a.remark)||(a==null?void 0:a.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Aa,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:r=>y(r.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),f.map(r=>e.jsx("option",{value:r.id,children:je(r.id)},r.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(is,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:F,onChange:r=>p(r.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:je(r.id)},r.id))]})]})]}),e.jsxs("button",{onClick:Q,disabled:W||!F,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Ue,{className:`w-4 h-4 ${W?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Ve,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Xe,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ae,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Fs,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void he(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(ws,{className:"w-4 h-4"}),Z&&["running","canceling"].includes(Z.status)?"继续批量任务":"批量铺货"]}),Z&&!["running","canceling"].includes(Z.status)&&e.jsx("button",{onClick:()=>void $e(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[me.map(r=>{const a=Ge(r),u=a.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex
Line truncated
|
||||
@@ -0,0 +1,19 @@
|
||||
import{j as e,r as i,b as Le,c as ba,d as ya}from"./react-vendor-DZnRGM0-.js";import{L as fa,U as Ut,S as Wt,C as Ys,B as Vt,Z as Zs,a as ps,b as rt,c as Gt,d as ja,e as ns,A as ht,D as Na,f as gt,P as Jt,g as ks,E as Qt,T as va,h as wa,i as Re,Q as zs,j as is,k as He,l as us,m as bt,R as Oe,n as Kt,o as _a,p as Je,X as _e,K as ka,q as rs,r as as,s as ss,t as es,u as yt,v as nt,w as hs,x as Yt,y as Zt,z as _s,F as Xt,G as Ca,H as ft,I as jt,J as Sa,M as La,N as Aa,O as Ia,V as Us,W as As,Y as Ht,_ as $a,$ as Ra,a0 as Xs,a1 as Pa,a2 as Da,a3 as Hs,a4 as Nt,a5 as Fa,a6 as Fs,a7 as ea,a8 as Ta,a9 as Ea,aa as it,ab as sa,ac as Ma,ad as Oa}from"./icons-vendor-RenKjhri.js";import{R as Is,B as qa,X as vt,Y as wt,T as Ws,a as Ba,C as Vs,A as za,b as Ua,c as Wa,P as _t,d as kt,L as Va}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const x of document.querySelectorAll('link[rel="modulepreload"]'))d(x);new MutationObserver(x=>{for(const N of x)if(N.type==="childList")for(const S of N.addedNodes)S.tagName==="LINK"&&S.rel==="modulepreload"&&d(S)}).observe(document,{childList:!0,subtree:!0});function n(x){const N={};return x.integrity&&(N.integrity=x.integrity),x.referrerPolicy&&(N.referrerPolicy=x.referrerPolicy),x.crossOrigin==="use-credentials"?N.credentials="include":x.crossOrigin==="anonymous"?N.credentials="omit":N.credentials="same-origin",N}function d(x){if(x.ep)return;x.ep=!0;const N=n(x);fetch(x.href,N)}})();const Ga=({className:s="w-full h-full text-white"})=>e.jsx("svg",{className:s,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),et=({sizeClass:s="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${s} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Ls,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:v,children:"取消"}),e.jsxs("button",{onClick:os,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:v,children:[v?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(ss,{className:"w-4 h-4"}),v?"保存中...":"保存"]})]})})]})}),document.body)]})},Nr=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),vr=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],Dt=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},n={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:n[s]||s})},wr=()=>{const[s,t]=i.useState([]),[n,d]=i.useState([]),[x,N]=i.useState([]),[S,F]=i.useState({}),[h,R]=i.useState("all"),[b,J]=i.useState(""),[ae,le]=i.useState(""),[oe,k]=i.useState(""),B=i.useRef(0),[re,Q]=i.useState(1),[H,z]=i.useState(1),[xe,ce]=i.useState(!1),[w,D]=i.useState(!1),[U,G]=i.useState(!1),[me,A]=i.useState(!1),[I,Z]=i.useState(null),[L,se]=i.useState(null),[ee,ke]=i.useState({}),[T,m]=i.useState(!1),[g,E]=i.useState(""),[P,ne]=i.useState(!1),[ge,K]=i.useState(null),[ye,C]=i.useState(null),[o,_]=i.useState(null),[r,v]=i.useState(!1),[O,V]=i.useState(null),[q,he]=i.useState(null),te=async()=>{const u=++B.current;ce(!0);try{const $=await yl(b||void 0,h,re,20,oe);if(u!==B.current)return;t($.data),z($.total_pages)}catch($){console.error("加载订单失败:",$)}finally{u===B.current&&ce(!1)}},ue=(u,$,ie)=>{if(ie&&ie.trim())return ie;if(S[`${u}:${$}`])return S[`${u}:${$}`];const we=n.find(Ke=>{if(ie&&Ke.item_title){const Ye=ie.toLowerCase(),Ue=Ke.item_title.toLowerCase();return Ue.includes(Ye)||Ye.includes(Ue)}return!1});return we!=null&&we.item_title?we.item_title:"未知商品"},Ie=u=>{const $={};u.forEach(ie=>{ie.item_id&&($[`${ie.cookie_id}:${ie.item_id}`]=ie.item_title||ie.item_id)}),F($)};i.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),k(ae.trim())},300);return()=>window.clearTimeout(u)},[ae]),i.useEffect(()=>{te()},[b,h,re,oe]),i.useEffect(()=>{Promise.all([Ms(),gs()]).then(([u,$])=>{N(u),d($),Ie($)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const ve=i.useMemo(()=>new Map(x.map(u=>[u.id,u])),[x]),Ve=u=>{const $=ve.get(u),ie=($==null?void 0:$.remark)||($==null?void 0:$.nickname);return ie?`${ie} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},$e=u=>{const $=ve.get(u);return($==null?void 0:$.remark)||($==null?void 0:$.nickname)||"未命名账号"},Te=async()=>{ce(!0);try{const u=await Nl(b||void 0,h);await te(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{ce(!1)}},qe=u=>{E(u),K(null),m(!0)},Ee=async u=>{var $;ne(!0),K(null);try{const ie=await wl([g],u),we=($=ie==null?void 0:ie.results)==null?void 0:$[0];we!=null&&we.success?(K({success:!0,message:we.message}),te()):K({success:!1,message:(we==null?void 0:we.message)||"发货失败"})}catch(ie){K({success:!1,message:(ie==null?void 0:ie.message)||"请求失败"})}finally{ne(!1)}},Ge=u=>{Z(u),D(!0)},Be=u=>{se({...u}),G(!0)},Pe=async()=>{if(!(!L||!L.order_id))try{const u={};L.status!==void 0&&(u.order_status=L.status),L.buyer_id!==void 0&&(u.buyer_id=L.buyer_id),L.amount!==void 0&&(u.amount=L.amount),L.receiver_name!==void 0&&(u.receiver_name=L.receiver_name),L.receiver_
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(q=>q.map(he=>`"${String(he).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),v=new Blob(["\uFEFF"+r],{type:"text/csv;charset=utf-8"}),O=URL.createObjectURL(v),V=document.createElement("a");V.href=O,V.download="卡密组批量导入模板.csv",document.body.appendChild(V),V.click(),V.remove(),URL.revokeObjectURL(O)},K=async()=>{if(B){xe(!0),H(null);try{const o=await Il(B);if(H(o),o.created>0){const _=await Xe();t(_)}}catch(o){H({error:(o==null?void 0:o.message)||"上传失败"})}finally{xe(!1)}}},ye=async()=>{if(!(!ce||!D.trim())){xe(!0),me(null);try{const o=await $l(ce,D);me({added:o.added}),U("");const _=await Xe();t(_)}catch(o){alert("追加失败:"+((o==null?void 0:o.message)||"未知错误"))}finally{xe(!1)}}},C=()=>{var o;k("create"),re(null),H(null),w((o=P[0])!=null&&o.id?String(P[0].id):""),U(""),me(null),le(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:C,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(_s,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>N(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(es,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Xt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:A,onChange:o=>I(o.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(nt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:Z,onChange:o=>L(o.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",ne.length," / ",s.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:ne.map(o=>{let _="";return o.type==="data"&&o.data_content?_=`库存: ${o.data_content.split(`
|
||||
`).filter(v=>v.trim()).length} 条`:o.type==="text"&&o.text_content?_=o.text_content:o.type==="api"&&o.api_config?_=o.api_config.url:o.type==="image"&&o.image_url&&(_="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(se,{type:o.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:o.name,children:o.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>E(o.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:o.id}),e.jsx(Ca,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${o.type==="text"?"bg-blue-50 text-blue-600":o.type==="data"?"bg-purple-50 text-purple-600":o.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:o.type==="text"?"文本":o.type==="data"?"批量":o.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:_,children:_})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:o.description||"-",children:o.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>g(o),className:`w-12 h-8 rounded-full relative transition-colors ${o.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${o.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>ee(o),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(hs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>T(o.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},o.id)})})]})}),ne.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Jt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:s.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),n&&S&&Le.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>d(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(_e,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:h.name||"",onChange:o=>R({...h,name:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:h.type||"text",onChange:o=>R({...h,type:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(S==null?void 0:S.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),h.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:h.api_url||"",onChange:o=>R({...h,api_url:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxLine truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:h.data_content?h.data_content.split(`
|
||||
`).filter(o=>o.trim()).length:0})," 条"]})]})]}),h.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:h.image_url||"",onChange:o=>R({...h,image_url:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),h.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:h.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:o=>{o.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:h.delay_seconds||0,onChange:o=>R({...h,delay_seconds:parseInt(o.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:h.description||"",onChange:o=>R({...h,description:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>R({...h,enabled:!h.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${h.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${h.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>d(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ke,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ss,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),x&&Le.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>N(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(_e,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:b.name,onChange:o=>J({...b,name:o.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>J({...b,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Ys,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>J({...b,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ft,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>J({...b,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-grayLine truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),b.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:b.content.split(`
|
||||
`).filter(o=>o.trim()).length})," 条"]})]}),b.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:b.api_method,onChange:o=>J({...b,api_method:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:b.api_timeout,onChange:o=>J({...b,api_timeout:parseInt(o.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:b.api_headers,onChange:o=>J({...b,api_headers:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:b.api_params,onChange:o=>J({...b,api_params:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:b.description,onChange:o=>J({...b,description:o.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:b.delay_seconds,onChange:o=>J({...b,delay_seconds:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>N(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:m,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),ae&&Le.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>le(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(_e,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>k("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Sa,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>k("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(_s,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),oe==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:ge,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 tex
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),G&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",G.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>le(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),oe==="create"?e.jsxs("button",{onClick:K,disabled:!B||z,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[z?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(_s,{className:"w-4 h-4"}),z?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:ye,disabled:!ce||!D.trim()||z||P.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[z?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(es,{className:"w-4 h-4"}),z?"处理中...":"追加卡密"]})]})]})}),document.body)]})},Cr=s=>s.find(t=>t.status==="running"||t.status==="canceling"),Sr=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},Lr=({onConfigureDelivery:s})=>{const[t,n]=i.useState([]),[d,x]=i.useState([]),[N,S]=i.useState([]),[F,h]=i.useState(""),[R,b]=i.useState(""),[J,ae]=i.useState(!1),[le,oe]=i.useState(!1),[k,B]=i.useState(!1),[re,Q]=i.useState(!1),[H,z]=i.useState(!1),[xe,ce]=i.useState(!1),[w,D]=i.useState(!1),[U,G]=i.useState("upload"),[me,A]=i.useState(null),[I,Z]=i.useState(null),[L,se]=i.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[ee,ke]=i.useState(null),[T,m]=i.useState(null),[g,E]=i.useState(null),P=i.useRef(!1),[ne,ge]=i.useState(null),[K,ye]=i.useState({}),[C,o]=i.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[_,r]=i.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[v,O]=i.useState([]),V=i.useMemo(()=>{const l=new Map;return t.forEach(y=>{const Y=String(y.item_category||"").trim();if(!Y)return;let Ce="";try{const Me=JSON.parse(y.item_detail||"{}");Ce=String(Me.category_name||"").trim()}catch{}(!l.has(Y)||Ce)&&l.set(Y,Ce)}),Array.from(l,([y,Y])=>({catId:y,catName:Y}))},[t]);i.useEffect(()=>{if(!xe||_.images.length===0){O([]);return}const l=_.images.map((y,Y)=>({key:y.name+Y,url:URL.createObjectURL(y)}));return O(l),()=>{l.forEach(y=>URL.revokeObjectURL(y.url))}},[xe,_.images]);const q=async()=>{const l=await gs();n(l)},he=async()=>{x(await tt())};i.useEffect(()=>{Promise.all([Ms(),gs(),tt(),At(20)]).then(([l,y,Y,Ce])=>{S(l),n(y),x(Y);const Me=Ce.find(De=>["running","canceling"].includes(De.status))||Ce.find(De=>De.status!=="preview");E(Me||null)}).catch(l=>console.error("加载商品配置失败:",l))},[]),i.useEffect(()=>{if(!w||!(T!=null&&T.id)||!["running","canceling"].includes(T.status))return;const l=window.setInterval(async()=>{if(!P.current){P.current=!0;try{const y=await xs(T.id);m(y),E(y),["running","canceling"].includes(y.status)||(G("done"),await q(),await he())}catch(y){console.error("刷新批量铺货进度失败:",y)}finally{P.current=!1}}},3e3);return()=>{window.clearInterval(l)}},[w,T==null?void 0:T.id,T==null?void 0:T.status]);const te=async()=>{if(!F)return alert("请先选择账号");ae(!0);try{const l=await Rl(F);await q(),alert((l==null?void 0:l.message)||"商品同步完成")}catch(l){console.error("同步商品失败:",l),alert((l==null?void 0:l.message)||"同步失败,请重试")}finally{ae(!1)}},ue=l=>{ge(l),ye({...l}),Q(!0)},Ie=async()=>{if(ne)try{await Bl(ne.cookie_id,ne.item_id,{item_title:K.item_title||"",item_description:K.item_description||"",item_category:K.item_category||"",item_price:K.item_price||"",item_detail:K.item_detail||ne.item_detail||""}),await q(),await he(),Q(!1),ge(null)}catch(l){console.error("更新商品失败:",l),alert("更新失败,请重试")}},ve=async l=>{if(confirm(`确认删除商品"${l.item_title}"吗?`))try{await Pl(l.cookie_id,l.item_id),n(y=>y.filter(Y=>!(Y.cookie_id===l.cookie_id&&Y.item_id===l.item_id)))}catch(y){console.error("删除商品失败:",y),alert("删除失败,请重试")}},Ve=async()=>{try{if(!C.cookie_id||!C.item_id){alert("请选择账号并填写商品ID");return}await Dl(C.cookie_id,{item_id:C.item_id,item_title:C.item_title,item_price:C.item_price,item_detail:C.item_image?JSON.stringify({item_image:C.item_image}):""}),await q(),z(!1),o({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(l){console.error("添加商品失败:",l),alert("添加失败,请重试")}},$e=async()=>{if(!_.cookie_id)return alert("请选择发布账号");if(!_.title.trim())return alert("请填写商品标
Line truncated
|
||||
`),Ce=new Blob(["\uFEFF"+Y],{type:"text/csv;charset=utf-8"}),Me=URL.createObjectURL(Ce),De=document.createElement("a");De.href=Me,De.download="批量铺货模板.csv",document.body.appendChild(De),De.click(),De.remove(),URL.revokeObjectURL(Me)},ze=()=>{o(l=>({...l,cookie_id:F||l.cookie_id})),z(!0)},u=()=>{r(l=>({...l,cookie_id:F||l.cookie_id})),ce(!0)},$=l=>d.filter(y=>y.cookie_id===l.cookie_id&&y.item_id===l.item_id).length>0?d.filter(y=>y.cookie_id===l.cookie_id&&y.item_id===l.item_id):d.filter(y=>y.cookie_id===l.cookie_id&&!y.item_id),ie=l=>{switch(l){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return l||"-"}},we=l=>{switch(l){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Ke=i.useMemo(()=>new Map(N.map(l=>[l.id,l])),[N]),Ye=i.useMemo(()=>R?t.filter(l=>l.cookie_id===R):t,[R,t]),Ue=l=>{const y=Ke.get(l),Y=(y==null?void 0:y.remark)||(y==null?void 0:y.nickname);return Y?`${Y} · ${l.slice(0,6)}`:`账号 ${l.slice(0,8)}`},We=l=>{const y=Ke.get(l);return(y==null?void 0:y.remark)||(y==null?void 0:y.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ia,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:R,onChange:l=>b(l.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),N.map(l=>e.jsx("option",{value:l.id,children:Ue(l.id)},l.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(is,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:F,onChange:l=>h(l.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),N.map(l=>e.jsx("option",{value:l.id,children:Ue(l.id)},l.id))]})]})]}),e.jsxs("button",{onClick:te,disabled:J||!F,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Oe,{className:`w-4 h-4 ${J?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ze,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(es,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:u,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Us,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Te(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(As,{className:"w-4 h-4"}),g&&["running","canceling"].includes(g.status)?"继续批量任务":"批量铺货"]}),g&&!["running","canceling"].includes(g.status)&&e.jsx("button",{onClick:()=>void qe(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Ye.map(l=>{const y=$(l),Y=y.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex
Line truncated
|
||||
@@ -6,12 +6,12 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
|
||||
<script type="module" crossorigin src="/static/assets/index-CQt5Rx7p.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-D1qb4SVL.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-DZnRGM0-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-RenKjhri.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/vendor-w5t2K9ux.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-B_BfwiL0.js">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-BqT2f1O2.css">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-BgaWj1th.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -30,6 +30,10 @@ const (
|
||||
DefaultLocationAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.local.poi.get/1.0/"
|
||||
)
|
||||
|
||||
// ErrPublishCategoryUnrecognized 表示闲鱼类目推荐接口调用成功,但没有给出可发布类目。
|
||||
// 这是发生在最终发布接口之前的确定性结果,调用方可以安全地改用人工指定类目。
|
||||
var ErrPublishCategoryUnrecognized = errors.New("未能自动识别商品类目,请调整标题或图片后重试")
|
||||
|
||||
type PublishErrorCode string
|
||||
|
||||
const (
|
||||
@@ -60,6 +64,15 @@ type PublishImage struct {
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// PublishCategory 是发布商品时可使用的人工兜底类目。
|
||||
// CatID 和 CatName 必填;频道类目、淘宝类目 ID 没有时可以留空。
|
||||
type PublishCategory struct {
|
||||
CatID string `json:"cat_id"`
|
||||
CatName string `json:"cat_name"`
|
||||
ChannelCatID string `json:"channel_cat_id,omitempty"`
|
||||
TBCatID string `json:"tb_cat_id,omitempty"`
|
||||
}
|
||||
|
||||
type PublishItemRequest struct {
|
||||
Title string
|
||||
Description string
|
||||
@@ -69,8 +82,9 @@ type PublishItemRequest struct {
|
||||
PostageMode string
|
||||
PostageCents int64
|
||||
// Virtual 表示商品只通过系统的虚拟发货流程交付,不需要实物发货地址。
|
||||
Virtual bool
|
||||
Images []PublishImage
|
||||
Virtual bool
|
||||
FallbackCategory *PublishCategory
|
||||
Images []PublishImage
|
||||
}
|
||||
|
||||
type PublishItemResult struct {
|
||||
@@ -111,6 +125,9 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
|
||||
if len(req.Images) > 9 {
|
||||
return nil, errors.New("商品图片最多 9 张")
|
||||
}
|
||||
if req.FallbackCategory != nil && !validPublishCategory(*req.FallbackCategory) {
|
||||
return nil, errors.New("兜底类目必须同时填写类目 ID 和类目名称")
|
||||
}
|
||||
currentCookies := cookiesStr
|
||||
if session := cookieSessionFromContext(ctx); session != nil {
|
||||
currentCookies, _, _ = session.State()
|
||||
@@ -127,12 +144,16 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
|
||||
uploaded = append(uploaded, res)
|
||||
}
|
||||
category, updated, err := c.recommendPublishCategory(ctx, currentCookies, req.Title, req.Description, uploaded)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if updated != "" {
|
||||
currentCookies = updated
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrPublishCategoryUnrecognized) && req.FallbackCategory != nil {
|
||||
category = fallbackPublishCategory(*req.FallbackCategory)
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var location map[string]any
|
||||
if !req.Virtual {
|
||||
location, updated, err = c.defaultPublishLocation(ctx, currentCookies)
|
||||
@@ -253,15 +274,30 @@ func (c *ClientImpl) recommendPublishCategory(ctx context.Context, cookiesStr, t
|
||||
}
|
||||
dataMap := mapFromAny(decoded["data"])
|
||||
if dataMap == nil {
|
||||
return nil, updated, fmt.Errorf("类目推荐响应缺少 data")
|
||||
return nil, updated, fmt.Errorf("%w: 类目推荐响应缺少 data", ErrPublishCategoryUnrecognized)
|
||||
}
|
||||
cat := mapFromAny(dataMap["categoryPredictResult"])
|
||||
if cat == nil || mtopString(cat["catId"]) == "" {
|
||||
return nil, updated, fmt.Errorf("未能自动识别商品类目,请调整标题或图片后重试")
|
||||
return nil, updated, ErrPublishCategoryUnrecognized
|
||||
}
|
||||
return dataMap, updated, nil
|
||||
}
|
||||
|
||||
func validPublishCategory(category PublishCategory) bool {
|
||||
return strings.TrimSpace(category.CatID) != "" && strings.TrimSpace(category.CatName) != ""
|
||||
}
|
||||
|
||||
func fallbackPublishCategory(category PublishCategory) map[string]any {
|
||||
return map[string]any{
|
||||
"categoryPredictResult": map[string]any{
|
||||
"catId": strings.TrimSpace(category.CatID),
|
||||
"catName": strings.TrimSpace(category.CatName),
|
||||
"channelCatId": strings.TrimSpace(category.ChannelCatID),
|
||||
"tbCatId": strings.TrimSpace(category.TBCatID),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ClientImpl) defaultPublishLocation(ctx context.Context, cookiesStr string) (map[string]any, string, error) {
|
||||
data := map[string]any{"longitude": 118.78248347393424, "latitude": 31.91629189813543}
|
||||
decoded, updated, err := c.callMTop(ctx, cookiesStr, DefaultLocationAPI, "mtop.taobao.idle.local.poi.get", "1.0", "a21ybx.publish.0.0", "a21ybx.item.sidebar.1.38262218ame5nr", "38262218ame5nr", data)
|
||||
|
||||
@@ -61,6 +61,7 @@ func TestPublishItemValidationFailures(t *testing.T) {
|
||||
{"zero quantity", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 0, Images: []PublishImage{{}}}, "库存数量必须大于 0"},
|
||||
{"no images", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 1}, "至少上传 1 张商品图片"},
|
||||
{"too many images", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 1, Images: make([]PublishImage, 10)}, "商品图片最多 9 张"},
|
||||
{"incomplete fallback category", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 1, FallbackCategory: &PublishCategory{CatID: "5001"}, Images: []PublishImage{{}}}, "兜底类目必须同时填写"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
@@ -139,10 +140,11 @@ func TestPublishItemUploadImageFailure(t *testing.T) {
|
||||
}}
|
||||
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
|
||||
req := PublishItemRequest{
|
||||
Title: "T",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
Title: "T",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
FallbackCategory: &PublishCategory{CatID: "5001", CatName: "虚拟商品"},
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
}
|
||||
_, err := client.PublishItem(context.Background(), consignCookies, req)
|
||||
if err == nil || !strings.Contains(err.Error(), "图片上传响应缺少 url") {
|
||||
@@ -163,10 +165,11 @@ func TestPublishItemRecommendCategoryFailure(t *testing.T) {
|
||||
}}
|
||||
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
|
||||
req := PublishItemRequest{
|
||||
Title: "T",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
Title: "T",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
FallbackCategory: &PublishCategory{CatID: "5001", CatName: "虚拟商品"},
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
}
|
||||
_, err := client.PublishItem(context.Background(), consignCookies, req)
|
||||
if err == nil {
|
||||
@@ -200,6 +203,9 @@ func TestPublishItemRecommendCategoryMissingData(t *testing.T) {
|
||||
if err == nil || !strings.Contains(err.Error(), "未能自动识别商品类目") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if !errors.Is(err, ErrPublishCategoryUnrecognized) {
|
||||
t.Fatalf("err=%v want ErrPublishCategoryUnrecognized", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemLocationFailure: 默认地址缺失。
|
||||
@@ -267,6 +273,45 @@ func TestPublishVirtualItemSkipsLocation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishVirtualItemUsesFallbackCategoryWhenRecommendationIsEmpty(t *testing.T) {
|
||||
png1 := tinyPNG(t)
|
||||
var publishedData map[string]any
|
||||
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
|
||||
"_upload": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
|
||||
},
|
||||
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
|
||||
},
|
||||
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, r *http.Request) {
|
||||
publishedData, _ = parseDataURL(readBody(r))
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"fallback-item-1"}}`)
|
||||
},
|
||||
}}
|
||||
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
|
||||
res, err := client.PublishItem(context.Background(), consignCookies, PublishItemRequest{
|
||||
Title: "虚拟商品",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
Virtual: true,
|
||||
FallbackCategory: &PublishCategory{CatID: "5001", CatName: "虚拟服务", ChannelCatID: "6001", TBCatID: "7001"},
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if res.CategoryID != "5001" || res.CategoryName != "虚拟服务" {
|
||||
t.Fatalf("category result=%+v", res)
|
||||
}
|
||||
category, _ := publishedData["itemCatDTO"].(map[string]any)
|
||||
if category["catId"] != "5001" || category["catName"] != "虚拟服务" || category["channelCatId"] != "6001" || category["tbCatId"] != "7001" {
|
||||
t.Fatalf("published category=%+v", category)
|
||||
}
|
||||
if _, exists := publishedData["itemAddrDTO"]; exists {
|
||||
t.Fatalf("虚拟商品不应发送 itemAddrDTO: %+v", publishedData["itemAddrDTO"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemFinalPublishFailure: 发布接口返回 token 过期错误。
|
||||
func TestPublishItemFinalPublishFailure(t *testing.T) {
|
||||
png1 := tinyPNG(t)
|
||||
|
||||
Reference in new issue
Block a user