From 3f7954af84072ca86342603f7ab35560930902cc Mon Sep 17 00:00:00 2001 From: Christ Date: Mon, 6 Jul 2026 12:27:37 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20token=20=E4=BF=9D=E6=B4=BB=20+=20?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=E7=B3=BB=E7=BB=9F=20+=20=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E9=93=BA=E8=B4=A7=20+=20=E5=8D=A1=E5=AF=86=E6=89=B9=E9=87=8F?= =?UTF-8?q?=20+=20=E5=89=8D=E7=AB=AF=E8=B7=AF=E7=94=B1=E4=B8=8E=E6=A0=B7?= =?UTF-8?q?=E5=BC=8F=E5=AF=B9=E9=BD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端 - token 刷新:session 过期立即触发密码登录兜底(不再空跑5次冷却); FAIL_SYS_SESSION_EXPIRED 识别为凭证失效;token 刷新成功日志; 在线定时刷新 token 间隔从 1h 调整为 15min,持续续期 cookie - QR 登录:修复自动验证成功状态被 EXPIRED 覆盖的竞态(前端拿不到 cookie) - 通知系统:Notifier 加 NotifyAccountAlert/SendToChannel;engine Handler 加 OnAccountAlert(warn/critical/风控三触发点);handlerAdapter 接 notifier; 通知渠道测试发送端点 POST /notification-channels/{id}/test; NotificationChannelRow 加 json tag 修复前端读不到字段 - 卡密批量:POST /cards/batch 批量创建卡密组;POST /cards/{id}/append-data 往 data 组充卡密;DB AppendBatchData - 通知渠道启用切换修复(全量更新避免 type CHECK 约束报错) 前端 - history 路由(/app/ 前缀避开 API 冲突,刷新不丢位置,popstate 同步) - 通知设置页:渠道管理 + 账号绑定 + 配置指南 + SMTP(从系统设置移入) - 卡密批量导入弹窗(批量建组 + 单组充卡密) - 商品卡片缩小约 2/3;Rules/Notifications 头部样式对齐标准页 - 初始化提示按 OS 区分命令(Windows/macOS) - updateChannel 全量更新修复启用切换失败 文档 - docs/批量铺货使用文档.md(给铺货 agent 的资料包准备规格) Co-Authored-By: Claude Opus 4.8 --- cmd/server/main.go | 12 + docs/批量铺货使用文档.md | 226 ++++++++ frontend/App.tsx | 57 +- frontend/components/AccountList.tsx | 79 ++- frontend/components/CardList.tsx | 242 ++++++++- frontend/components/Dashboard.tsx | 18 +- frontend/components/ItemList.tsx | 40 +- frontend/components/Notifications.tsx | 648 +++++++++++++++++++++++ frontend/components/OrderList.tsx | 2 +- frontend/components/Rules.tsx | 146 ++--- frontend/components/Settings.tsx | 95 +--- frontend/components/Sidebar.tsx | 9 +- frontend/index.css | 10 +- frontend/services/api.ts | 35 +- frontend/tailwind.config.js | 11 +- frontend/types.ts | 13 + internal/account/manager_test.go | 1 + internal/db/delivery.go | 33 ++ internal/db/extras.go | 26 +- internal/engine/account.go | 90 +++- internal/engine/engine_test.go | 5 +- internal/notify/notifier.go | 47 ++ internal/server/card_batch_handlers.go | 172 ++++++ internal/server/card_handlers.go | 2 + internal/server/notification_handlers.go | 22 + internal/server/server_test.go | 1 + internal/webui/static/index.html | 4 +- internal/xianyu/mtop/client.go | 16 +- internal/xianyu/qrlogin/client.go | 16 +- internal/xianyu/ws/client.go | 7 + 30 files changed, 1826 insertions(+), 259 deletions(-) create mode 100644 docs/批量铺货使用文档.md create mode 100644 frontend/components/Notifications.tsx create mode 100644 internal/server/card_batch_handlers.go diff --git a/cmd/server/main.go b/cmd/server/main.go index f7aff72..d1f8bdc 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -90,6 +90,7 @@ func main() { notifier := notify.New("", store, logger) autoCenter.SetNotifier(notifier) adapter.automation = autoCenter + adapter.notifier = notifier if err := mgr.StartAll(ctx); err != nil { logger.Error("启动账号引擎失败", "err", err) } @@ -122,6 +123,7 @@ type handlerAdapter struct { browser *browser.Manager logger *slog.Logger automation *automation.Center + notifier *notify.Notifier mu sync.Mutex lastLoginByCID map[string]time.Time @@ -133,6 +135,16 @@ func (h *handlerAdapter) HandleChatMessage(ctx context.Context, m engine.ChatMes return nil } +// OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器, +// 推送到该账号已绑定的通知渠道。 +func (h *handlerAdapter) OnAccountAlert(_ context.Context, cookieID, level, title, body string) { + if h.notifier == nil { + h.logger.Warn("告警通知未发送:通知器未注入", "account", cookieID, "level", level, "title", title) + return + } + h.notifier.NotifyAccountAlert(cookieID, level, title, body) +} + func (h *handlerAdapter) HandleSystemEvent(ctx context.Context, task automation.Task) error { if h.automation == nil { return nil diff --git a/docs/批量铺货使用文档.md b/docs/批量铺货使用文档.md new file mode 100644 index 0000000..4f20ef9 --- /dev/null +++ b/docs/批量铺货使用文档.md @@ -0,0 +1,226 @@ +# 批量铺货资料包准备规格(AI Agent 指南) + +> 本文档面向负责**准备资料**的 AI agent。你的任务是产出一份符合规格的商品表格(和可选的图片压缩包),交给运营人员通过后台"批量铺货"功能上传上架。 +> +> **你不负责提交上传、不负责调用接口、不负责跑发布流程。** 你只产出文件。下面是文件必须满足的规格。 + +--- + +## 1. 你的交付物 + +| 交付物 | 必填 | 格式 | 说明 | +|---|---|---|---| +| 商品表格 | 是 | `.csv` / `.xlsx` / `.tsv` | 每行一个商品,第一行表头 | +| 图片压缩包 | 条件必填 | `.zip` | 仅当表格里有图片用本地路径引用时才需要;全用公网 URL 则不需要 | + +**命名建议:** +- 表格:`商品清单_YYYYMMDD.csv`(或 `.xlsx`) +- 图片包:`images.zip`(或 `图片包_YYYYMMDD.zip`) + +把两个文件放在同一目录交付即可。 + +--- + +## 2. 表格规格 + +### 2.1 表头(第一行) + +表头必须完全一致(大小写敏感、无空格)。**推荐用中文表头**,复制下面这一行: + +``` +账号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 +``` + +> 中英文表头二选一,**不要混用**。每个表头单元格的匹配是精确匹配,多空格、全角半角差异都会导致该列识别失败。 + +### 2.2 字段填写规则 + +#### 基础字段 + +| 列 | 必填 | 格式 / 取值 | 示例 | +|---|---|---|---| +| 账号ID | 是* | 闲鱼账号 ID(数字字符串)。*可留空,留空时由上传者在页面上指定默认账号 | `2222660684687` | +| 标题 | 是 | 文本,非空 | `会员组合包自动发货` | +| 描述 | 否 | 文本。留空时默认等于标题 | `下单后发送主卡和附赠卡。` | +| 价格 | 是 | 数字,单位元,必须 > 0 | `19.90` | +| 原价 | 否 | 数字,单位元。划线价 | `29.90` | +| 库存 | 否 | 整数,> 0,默认 1 | `10` | +| 邮费模式 | 否 | `free`(包邮,默认)或 `fixed`(固定邮费)。也接受 `包邮` / `固定邮费` | `free` | +| 邮费 | 条件必填 | 数字。邮费模式为 `fixed` 时必填;`free` 时留空 | `8.00` | +| 图片 | 是 | 1–9 张,多个用 `;` 分隔。每项是公网 URL 或图片包内相对路径 | `images/bundle-1.jpg;images/bundle-2.jpg` | + +#### 自动化字段(可选,不填或填"否"表示不启用) + +启用值接受:`1` / `true` / `yes` / `y` / `on` / `是` / `开启` / `启用`(不区分大小写)。 +不启用填:`0` / `false` / `no` / `否` / 留空。 + +| 列 | 何时必填 | 格式 | +|---|---|---| +| 付款发货启用 | 否 | 启用值 | +| 付款发货内容 | 启用时必填 | 卡密组配置,见 §3 | +| 评价赠品启用 | 否 | 启用值 | +| 评价赠品内容 | 启用时必填 | 卡密组配置,见 §3 | +| 求评价启用 | 否 | 启用值 | +| 求评价等待小时 | 否 | 整数,> 0,默认 72。发货后多少小时未评价才提醒 | +| 求评价文案 | 启用时必填 | 文本,提醒消息内容 | +| 求评价最多次数 | 否 | 整数,> 0,默认 1 | + +--- + +## 3. 卡密组配置格式 + +"付款发货内容"和"评价赠品内容"两列使用统一格式: + +``` +卡密组ID:每件份数:延迟秒;卡密组ID:每件份数:延迟秒 +``` + +**规则:** +- 多条之间用 `;`(分号)分隔。 +- `每件份数` 可省略,默认 `1`。 +- `延迟秒` 可省略,默认 `0`。 +- 卡密组 ID 必须是上传者已在"卡密库存"中创建好的组 ID(你准备资料时如果不知道 ID,留空并在交付说明里标注"需运营填卡密组 ID")。 + +**示例:** + +| 内容列填法 | 含义 | +|---|---| +| `101:1` | 从卡密组 101 发 1 份 | +| `101:1;102:2` | 卡密组 101 发 1 份 + 卡密组 102 发 2 份 | +| `101:1:0;102:2:30` | 卡密组 101 立即发 1 份;卡密组 102 延迟 30 秒后发 2 份 | + +--- + +## 4. 图片规格 + +每个商品必须 1–9 张图片。两种方式二选一(可混用): + +### 4.1 用公网 URL(推荐,无需图片包) + +直接在"图片"列填图片直链,多个用 `;` 分隔: + +``` +https://cdn.example.com/bundle-1.jpg;https://cdn.example.com/bundle-2.jpg +``` + +要求:`http(s)://` 开头,可公开访问,图片格式。 + +### 4.2 用本地图片(需交付图片包 ZIP) + +把所有图片打成一个 `.zip`,表格"图片"列填**相对 ZIP 根的路径**。 + +**ZIP 结构示例:** +``` +images.zip +├── bundle-1.jpg +├── bundle-2.jpg +└── sub/ + └── product.jpg +``` + +**表格"图片"列对应填法:** +``` +bundle-1.jpg;bundle-2.jpg +sub/product.jpg +``` + +**图片限制:** +- 单张图片最大 10 MiB。 +- 仅保留 `image/*` 类型(jpg / png / webp 等),其他文件自动忽略。 +- 整个 ZIP 最大 200 MiB。 +- 路径分隔符用正斜杠 `/`,不要用反斜杠。 +- 路径不要以 `/` 开头,不要包含 `..`。 + +--- + +## 5. 资料包必须通过的校验 + +资料包上传后系统会逐行预检。**你交付前请按下表自检每一行**,任一项不通过该行会被标记无效(不会上架): + +| 检查项 | 规则 | +|---|---| +| 账号ID | 非空(或上传者用默认账号),且必须是上传者已授权的账号 | +| 标题 | 非空 | +| 价格 | > 0 | +| 库存 | > 0(默认 1) | +| 邮费模式 | `free` 或 `fixed`(或 `包邮` / `固定邮费`) | +| 邮费 | 邮费模式为 `fixed` 时必填且 ≥ 0 | +| 图片 | 1–9 张;本地路径必须在 ZIP 内存在;URL 必须是合法 `http(s)://` | +| 付款发货 | 启用时:内容列必填至少一条卡密组;卡密组 ID 必须属于上传者;每件份数 > 0;延迟秒 ≥ 0 | +| 评价赠品 | 同上 | +| 求评价 | 启用时:等待小时 > 0、文案非空、最多次数 > 0 | + +--- + +## 6. 硬性限制 + +| 限制项 | 上限 | +|---|---| +| 单个资料包商品行数 | 50 条 | +| 表格文件大小 | 20 MiB | +| 图片 ZIP 大小 | 200 MiB | +| 单张图片大小 | 10 MiB | +| 单个商品图片数 | 9 张 | + +> 超过 50 条请拆成多个资料包分别交付。 + +--- + +## 7. 完整示例 + +### 7.1 仅发布商品、不绑自动化(最简) + +**表格 `商品清单.csv`:** +```csv +账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数 +2222660684687,普通商品,仅发布不绑自动化,49.90,,10,fixed,8.00,https://cdn.example.com/p1.jpg,否,,,,否,,, +``` + +无需图片包(用的是 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,否,,否,,, +``` + +**图片包 `images.zip`:** +``` +images.zip +└── images/ + ├── bundle-1.jpg + ├── bundle-2.jpg + └── single.jpg +``` + +> 注意:表格里填 `images/bundle-1.jpg`,对应 ZIP 内 `images/bundle-1.jpg` 路径。 + +--- + +## 8. 交付前自检清单 + +逐项确认后再交付: + +- [ ] 表格第一行是表头,且和 §2.1 完全一致(中或英,不混用) +- [ ] 每行都有账号ID(或确认上传者会用默认账号) +- [ ] 每行标题非空、价格 > 0、库存 > 0 +- [ ] 邮费模式只填 `free` / `fixed`(或 `包邮` / `固定邮费`);`fixed` 时邮费已填 +- [ ] 每行图片 1–9 张,多个用 `;` 分隔 +- [ ] 用本地路径的图片,在 ZIP 内对应路径都能找到 +- [ ] 用 URL 的图片,链接是 `http(s)://` 且可公开访问 +- [ ] 启用了付款发货/评价赠品的行,内容列按 §3 格式填写,卡密组 ID 已知(或已标注需运营补填) +- [ ] 启用了求评价的行,等待小时 > 0、文案非空、最多次数 > 0 +- [ ] 总行数 ≤ 50;超过请拆包 +- [ ] 表格文件 ≤ 20 MiB;图片 ZIP ≤ 200 MiB;单图 ≤ 10 MiB +- [ ] CSV 用 UTF-8 编码(建议带 BOM,Excel 打开不乱码) + +满足以上,资料包即可直接上传,预检会全部通过。 diff --git a/frontend/App.tsx b/frontend/App.tsx index 6526832..017870b 100644 --- a/frontend/App.tsx +++ b/frontend/App.tsx @@ -7,6 +7,7 @@ import CardList from './components/CardList'; import ItemList from './components/ItemList'; import Settings from './components/Settings'; import Rules from './components/Rules'; +import Notifications from './components/Notifications'; import { login, verifySession } from './services/api'; import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react'; @@ -16,9 +17,30 @@ interface DeliveryRuleTarget { requestId: number; } +// 路由:URL path ↔ tab id。所有 SPA 路由统一挂 /app/ 前缀,避免和后端 API +// 路径(/orders、/cards、/items 等)冲突——后者在 chi 里先注册,刷新会直接 +// 返回 JSON 而不是 SPA 页面。 +const ROUTES: Record = { + '/app/dashboard': 'dashboard', + '/app/accounts': 'accounts', + '/app/orders': 'orders', + '/app/cards': 'cards', + '/app/items': 'items', + '/app/rules': 'rules', + '/app/notifications': 'notifications', + '/app/settings': 'settings', +}; +const TAB_TO_PATH: Record = Object.fromEntries( + Object.entries(ROUTES).map(([path, tab]) => [tab, path]) +); +const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard'; + +// 检测 Windows 以显示对应的 CLI 命令(路径分隔符、引号、.exe 后缀)。 +const isWindows = /Win/i.test(navigator.platform || navigator.userAgent); + const App: React.FC = () => { const [isLoggedIn, setIsLoggedIn] = useState(false); - const [activeTab, setActiveTab] = useState('dashboard'); + const [activeTab, setActiveTab] = useState(tabFromPath); const [checkingAuth, setCheckingAuth] = useState(true); const [needsInit, setNeedsInit] = useState(false); const [username, setUsername] = useState(''); @@ -27,6 +49,22 @@ const App: React.FC = () => { const [loginError, setLoginError] = useState(''); const [deliveryRuleTarget, setDeliveryRuleTarget] = useState(); + // 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。 + const navigate = (tab: string) => { + const path = TAB_TO_PATH[tab]; + if (path && path !== window.location.pathname) { + window.history.pushState({}, '', path); + } + setActiveTab(tab); + }; + + // 浏览器后退/前进同步 tab。 + useEffect(() => { + const onPopState = () => setActiveTab(tabFromPath()); + window.addEventListener('popstate', onPopState); + return () => window.removeEventListener('popstate', onPopState); + }, []); + // Check auth on mount useEffect(() => { verifySession() @@ -84,7 +122,7 @@ const App: React.FC = () => {
-
+
Ydisks @@ -96,7 +134,9 @@ const App: React.FC = () => {
请在服务器上执行:
-
./xianyu-server -init-admin -db data/xianyu_data.db -admin-password '请设置密码'
+
{isWindows
+                ? '.\\xianyu-server.exe -init-admin -db data\\xianyu_data.db -admin-password "请设置密码"'
+                : './xianyu-server -init-admin -db data/xianyu_data.db -admin-password \'请设置密码\''}
完成后刷新页面即可进入登录。
@@ -125,7 +165,7 @@ const App: React.FC = () => {
-
+
{/* Header with Logo */}
@@ -196,12 +236,13 @@ const App: React.FC = () => { case 'cards': return ; case 'items': return { setDeliveryRuleTarget({ cookieId: item.cookie_id, itemId: item.item_id, requestId: Date.now() }); - setActiveTab('rules'); + navigate('rules'); }} />; case 'rules': return setDeliveryRuleTarget(undefined)} />; + case 'notifications': return ; case 'settings': return ; default: return ; } @@ -209,9 +250,9 @@ const App: React.FC = () => { return (
- { setIsLoggedIn(false); }} diff --git a/frontend/components/AccountList.tsx b/frontend/components/AccountList.tsx index 8ff9fa6..8a6ea9b 100644 --- a/frontend/components/AccountList.tsx +++ b/frontend/components/AccountList.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; -import { AccountDetail, AIReplySettings } from '../types'; +import { AccountDetail, AIReplySettings, NotificationChannel } from '../types'; import { getAccountDetails, getAccountRuntimeStatuses, @@ -18,12 +18,15 @@ import { updateAccountLoginInfo, updateAccountAISettings, getAllAISettings, - getAccountAISettings + getAccountAISettings, + getNotificationChannels, + getAccountBindings, + setAccountBindings, } from '../services/api'; import { Plus, Power, Edit2, Trash2, QrCode, X, Check, Loader2, RefreshCw, Save, User, Clock, MessageCircle, - Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, ExternalLink + Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, ExternalLink, Bell } from 'lucide-react'; type ModalType = 'edit' | 'ai-settings' | null; @@ -43,6 +46,10 @@ const AccountList: React.FC = () => { const [activeModal, setActiveModal] = useState(null); const [editingAccount, setEditingAccount] = useState(null); + // 通知渠道绑定(编辑弹窗用) + const [notifChannels, setNotifChannels] = useState([]); + const [selectedChannelIds, setSelectedChannelIds] = useState([]); + // 编辑表单状态 const [editForm, setEditForm] = useState({ remark: '', @@ -174,7 +181,7 @@ const AccountList: React.FC = () => { } }; - const openEditModal = (account: AccountDetail) => { + const openEditModal = async (account: AccountDetail) => { setEditingAccount(account); setEditForm({ remark: account.remark || account.note || '', @@ -187,6 +194,19 @@ const AccountList: React.FC = () => { showLoginPassword: false, }); setActiveModal('edit'); + // 并行加载通知渠道列表 + 当前账号已绑定渠道 + try { + const [chRes, bindings] = await Promise.all([ + getNotificationChannels(), + getAccountBindings(account.id).catch(() => [] as number[]), + ]); + setNotifChannels(chRes.data || []); + setSelectedChannelIds(bindings || []); + } catch (e) { + console.error('加载通知渠道绑定失败', e); + setNotifChannels([]); + setSelectedChannelIds([]); + } }; const openAIModal = async (account: AccountDetail) => { @@ -249,6 +269,9 @@ const AccountList: React.FC = () => { })); } + // 更新通知渠道绑定(覆盖式,总是提交以支持解绑) + promises.push(setAccountBindings(editingAccount.id, selectedChannelIds)); + await Promise.all(promises); setActiveModal(null); loadAccounts(); @@ -419,17 +442,17 @@ const AccountList: React.FC = () => { const runtime = runtimePresentation(account); const requiresLogin = account.runtime_state === 'auth_expired' || account.runtime_state === 'verification_required'; return ( -
+
{account.avatar_url ? ( {account.nickname ) : ( -
+
)} @@ -566,7 +589,7 @@ const AccountList: React.FC = () => { : '请打开闲鱼APP扫描下方二维码'}

-
+
{qrStatus === 'loading' && } {qrStatus === 'waiting' && QR Code} {qrStatus === 'success' && ( @@ -761,6 +784,46 @@ const AccountList: React.FC = () => {
+ + {/* 通知渠道绑定 */} + {notifChannels.length > 0 && ( +
+

+ + 通知渠道绑定 +

+

勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道

+
+ {notifChannels.map(ch => { + const checked = selectedChannelIds.includes(Number(ch.id)); + return ( + + ); + })} +
+
+ )}
diff --git a/frontend/components/CardList.tsx b/frontend/components/CardList.tsx index 9dfd581..be78a47 100644 --- a/frontend/components/CardList.tsx +++ b/frontend/components/CardList.tsx @@ -1,8 +1,8 @@ import React, { useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; import { Card } from '../types'; -import { getCards, createCard, updateCard, deleteCard } from '../services/api'; -import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy } from 'lucide-react'; +import { getCards, createCard, updateCard, deleteCard, batchCreateCards, appendCardData } from '../services/api'; +import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, FileDown, ListPlus } from 'lucide-react'; type AddCardForm = { name: string; @@ -38,6 +38,16 @@ const CardList: React.FC = () => { const [editForm, setEditForm] = useState>({}); const [addForm, setAddForm] = useState(emptyAddForm); + // 批量导入 + const [showBatchModal, setShowBatchModal] = useState(false); + const [batchTab, setBatchTab] = useState<'create' | 'append'>('create'); + const [batchFile, setBatchFile] = useState(null); + const [batchResult, setBatchResult] = useState(null); + const [batchBusy, setBatchBusy] = useState(false); + const [appendTargetId, setAppendTargetId] = useState(''); + const [appendContent, setAppendContent] = useState(''); + const [appendResult, setAppendResult] = useState<{ added: number } | null>(null); + useEffect(() => { getCards().then(setCards); }, []); @@ -194,23 +204,100 @@ const CardList: React.FC = () => { } }; + const dataCards = cards.filter(c => c.type === 'data'); + + const downloadCardTemplate = () => { + const headers = ['名称', '类型', '内容', '描述', '启用', '延迟秒', '多规格', '规格名', '规格值']; + const rows = [ + ['VIP月卡', 'data', 'VIP-MONTH-001\nVIP-MONTH-002\nVIP-MONTH-003', '按行消费的卡密队列', '是', '0', '否', '', ''], + ['感谢文案', 'text', '感谢购买,如有问题联系客服~', '固定文本', '是', '0', '否', '', ''], + ['教程图', 'image', 'https://cdn.example.com/tutorial.jpg', '图片URL', '是', '0', '否', '', ''], + ]; + const csv = [headers, ...rows] + .map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')) + .join('\n'); + const blob = new Blob(['' + csv], { type: 'text/csv;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = '卡密组批量导入模板.csv'; + document.body.appendChild(link); + link.click(); + link.remove(); + URL.revokeObjectURL(url); + }; + + const handleBatchCreate = async () => { + if (!batchFile) return; + setBatchBusy(true); + setBatchResult(null); + try { + const res = await batchCreateCards(batchFile); + setBatchResult(res); + if (res.created > 0) { + const fresh = await getCards(); + setCards(fresh); + } + } catch (e: any) { + setBatchResult({ error: e?.message || '上传失败' }); + } finally { + setBatchBusy(false); + } + }; + + const handleBatchAppend = async () => { + if (!appendTargetId || !appendContent.trim()) return; + setBatchBusy(true); + setAppendResult(null); + try { + const res = await appendCardData(appendTargetId, appendContent); + setAppendResult({ added: res.added }); + setAppendContent(''); + const fresh = await getCards(); + setCards(fresh); + } catch (e: any) { + alert('追加失败:' + (e?.message || '未知错误')); + } finally { + setBatchBusy(false); + } + }; + + const openBatchModal = () => { + setBatchTab('create'); + setBatchFile(null); + setBatchResult(null); + setAppendTargetId(dataCards[0]?.id ? String(dataCards[0].id) : ''); + setAppendContent(''); + setAppendResult(null); + setShowBatchModal(true); + }; + return (
-
+
-

卡密库存

-

管理自动发货的卡密、链接或图片资源。

+

卡密库存

+

管理自动发货的卡密、链接或图片资源。

- + +
-
+
@@ -732,6 +819,147 @@ const CardList: React.FC = () => { , document.body )} + + {/* 批量导入弹窗 */} + {showBatchModal && createPortal( +
+
+
+

批量导入卡密

+ +
+ +
+ {/* Tab 切换 */} +
+ + +
+ + {batchTab === 'create' ? ( +
+
+ 上传表格,每行一个卡密组。表头:名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值。 + 类型填 text/data/image/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。 +
+
+ + +
+ {batchResult && !batchResult.error && ( +
+
+ 共 {batchResult.total} 行 · 成功 {batchResult.created} · 失败 {batchResult.failed} +
+ {batchResult.failed > 0 && ( +
+ {batchResult.rows.filter((r: any) => !r.success).map((r: any) => ( +
第 {r.row_no} 行「{r.name}」:{r.error}
+ ))} +
+ )} +
+ )} +
+ ) : ( +
+ {dataCards.length === 0 ? ( +
+ 暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。 +
+ ) : ( + <> +
+ + +
+
+ +