feat: token 保活 + 通知系统 + 批量铺货 + 卡密批量 + 前端路由与样式对齐
后端
- 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
cf109ae6ce
commit
3f7954af84
30 files changed
+1826
-259
No files matched your search
@@ -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
|
||||
|
||||
@@ -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 打开不乱码)
|
||||
|
||||
满足以上,资料包即可直接上传,预检会全部通过。
|
||||
+49
-8
@@ -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<string, string> = {
|
||||
'/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<string, string> = 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<DeliveryRuleTarget | undefined>();
|
||||
|
||||
// 切换 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 = () => {
|
||||
<div className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"></div>
|
||||
<div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse" style={{animationDelay: '2s'}}></div>
|
||||
|
||||
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-[3rem] shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in">
|
||||
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in">
|
||||
<div className="text-center mb-8">
|
||||
<div className="w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 p-4" style={{ filter: 'drop-shadow(0 8px 20px rgba(0,148,247,0.3))' }}>
|
||||
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full" />
|
||||
@@ -96,7 +134,9 @@ const App: React.FC = () => {
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 rounded-2xl bg-gray-50 border border-gray-100">
|
||||
<div className="text-sm font-bold text-gray-900 mb-2">请在服务器上执行:</div>
|
||||
<pre className="text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto">./xianyu-server -init-admin -db data/xianyu_data.db -admin-password '请设置密码'</pre>
|
||||
<pre className="text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto">{isWindows
|
||||
? '.\\xianyu-server.exe -init-admin -db data\\xianyu_data.db -admin-password "请设置密码"'
|
||||
: './xianyu-server -init-admin -db data/xianyu_data.db -admin-password \'请设置密码\''}</pre>
|
||||
<div className="text-xs text-gray-500 mt-2">完成后刷新页面即可进入登录。</div>
|
||||
</div>
|
||||
|
||||
@@ -125,7 +165,7 @@ const App: React.FC = () => {
|
||||
<div className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"></div>
|
||||
<div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse" style={{animationDelay: '2s'}}></div>
|
||||
|
||||
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-[3rem] shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-lg border border-white relative z-10 animate-fade-in">
|
||||
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-lg border border-white relative z-10 animate-fade-in">
|
||||
|
||||
{/* Header with Logo */}
|
||||
<div className="text-center mb-10">
|
||||
@@ -196,12 +236,13 @@ const App: React.FC = () => {
|
||||
case 'cards': return <CardList />;
|
||||
case 'items': return <ItemList onConfigureDelivery={(item) => {
|
||||
setDeliveryRuleTarget({ cookieId: item.cookie_id, itemId: item.item_id, requestId: Date.now() });
|
||||
setActiveTab('rules');
|
||||
navigate('rules');
|
||||
}} />;
|
||||
case 'rules': return <Rules
|
||||
initialDeliveryTarget={deliveryRuleTarget}
|
||||
onDeliveryTargetHandled={() => setDeliveryRuleTarget(undefined)}
|
||||
/>;
|
||||
case 'notifications': return <Notifications />;
|
||||
case 'settings': return <Settings />;
|
||||
default: return <Dashboard />;
|
||||
}
|
||||
@@ -209,9 +250,9 @@ const App: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen bg-[#F4F5F7] text-[#111]">
|
||||
<Sidebar
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
<Sidebar
|
||||
activeTab={activeTab}
|
||||
onNavigate={navigate}
|
||||
onLogout={() => {
|
||||
setIsLoggedIn(false);
|
||||
}}
|
||||
|
||||
@@ -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<ModalType>(null);
|
||||
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
|
||||
|
||||
// 通知渠道绑定(编辑弹窗用)
|
||||
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
|
||||
const [selectedChannelIds, setSelectedChannelIds] = useState<number[]>([]);
|
||||
|
||||
// 编辑表单状态
|
||||
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 (
|
||||
<div key={account.id} className="ios-card p-6 rounded-[2rem] flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300">
|
||||
<div key={account.id} className="ios-card p-6 rounded-xl flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300">
|
||||
<div className="flex items-center gap-5 sm:gap-8 min-w-0">
|
||||
<div className="relative">
|
||||
{account.avatar_url ? (
|
||||
<img
|
||||
src={account.avatar_url}
|
||||
alt={account.nickname || '账号头像'}
|
||||
className="w-20 h-20 rounded-3xl object-cover shadow-md ring-4 ring-white bg-gray-100"
|
||||
className="w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-20 h-20 rounded-3xl bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center">
|
||||
<div className="w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center">
|
||||
<User className="w-9 h-9" />
|
||||
</div>
|
||||
)}
|
||||
@@ -566,7 +589,7 @@ const AccountList: React.FC = () => {
|
||||
: '请打开闲鱼APP扫描下方二维码'}
|
||||
</p>
|
||||
|
||||
<div className="w-64 h-64 bg-[#F7F8FA] rounded-[2rem] mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-8 relative">
|
||||
<div className="w-64 h-64 bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-8 relative">
|
||||
{qrStatus === 'loading' && <Loader2 className="w-10 h-10 text-[#0094f7] animate-spin" />}
|
||||
{qrStatus === 'waiting' && <img src={qrCodeUrl} alt="QR Code" className="w-full h-full p-2" />}
|
||||
{qrStatus === 'success' && (
|
||||
@@ -761,6 +784,46 @@ const AccountList: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 通知渠道绑定 */}
|
||||
{notifChannels.length > 0 && (
|
||||
<div className="border-t border-gray-200 pt-6">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-1 flex items-center gap-2">
|
||||
<Bell className="w-5 h-5 text-blue-500" />
|
||||
通知渠道绑定
|
||||
</h3>
|
||||
<p className="text-xs text-gray-500 mb-4">勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道</p>
|
||||
<div className="space-y-2">
|
||||
{notifChannels.map(ch => {
|
||||
const checked = selectedChannelIds.includes(Number(ch.id));
|
||||
return (
|
||||
<label
|
||||
key={ch.id}
|
||||
className="flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSelectedChannelIds(prev =>
|
||||
checked ? prev.filter(id => id !== Number(ch.id)) : [...prev, Number(ch.id)]
|
||||
);
|
||||
}}
|
||||
className={`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${
|
||||
checked ? 'bg-[#0094f7] border-[#0094f7]' : 'bg-white border-gray-300'
|
||||
}`}
|
||||
>
|
||||
{checked && <Check className="w-3.5 h-3.5 text-white" />}
|
||||
</button>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-bold text-gray-900 text-sm">{ch.name}</div>
|
||||
<div className="text-xs text-gray-500">{ch.type}{ch.enabled ? '' : ' · 已停用'}</div>
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="modal-footer">
|
||||
|
||||
@@ -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<Partial<Card>>({});
|
||||
const [addForm, setAddForm] = useState<AddCardForm>(emptyAddForm);
|
||||
|
||||
// 批量导入
|
||||
const [showBatchModal, setShowBatchModal] = useState(false);
|
||||
const [batchTab, setBatchTab] = useState<'create' | 'append'>('create');
|
||||
const [batchFile, setBatchFile] = useState<File | null>(null);
|
||||
const [batchResult, setBatchResult] = useState<any>(null);
|
||||
const [batchBusy, setBatchBusy] = useState(false);
|
||||
const [appendTargetId, setAppendTargetId] = useState<string>('');
|
||||
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 (
|
||||
<div className="space-y-6 animate-fade-in">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-gray-900">卡密库存</h2>
|
||||
<p className="text-gray-500 mt-2 text-sm">管理自动发货的卡密、链接或图片资源。</p>
|
||||
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">卡密库存</h2>
|
||||
<p className="text-gray-500 mt-2 font-medium">管理自动发货的卡密、链接或图片资源。</p>
|
||||
</div>
|
||||
<button
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={openBatchModal}
|
||||
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"
|
||||
>
|
||||
<Upload className="w-5 h-5" />
|
||||
批量导入
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowAddModal(true)}
|
||||
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"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
添加新卡密
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ios-card rounded-[2rem] overflow-hidden shadow-lg border-0 bg-white">
|
||||
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
@@ -732,6 +819,147 @@ const CardList: React.FC = () => {
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
|
||||
{/* 批量导入弹窗 */}
|
||||
{showBatchModal && createPortal(
|
||||
<div className="modal-overlay">
|
||||
<div className="modal-container" style={{ maxWidth: '40rem' }}>
|
||||
<div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between">
|
||||
<h3 className="text-xl font-extrabold text-gray-900">批量导入卡密</h3>
|
||||
<button
|
||||
onClick={() => setShowBatchModal(false)}
|
||||
className="w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-600" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-5 space-y-5">
|
||||
{/* Tab 切换 */}
|
||||
<div className="flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl">
|
||||
<button
|
||||
onClick={() => setBatchTab('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 ${batchTab === 'create' ? 'bg-[#0094f7] text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
|
||||
>
|
||||
<ListPlus className="w-4 h-4" />
|
||||
批量创建卡密组
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setBatchTab('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 ${batchTab === 'append' ? 'bg-[#0094f7] text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
|
||||
>
|
||||
<Upload className="w-4 h-4" />
|
||||
往单个组充卡密
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{batchTab === 'create' ? (
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5">
|
||||
上传表格,每行一个卡密组。表头:<code className="bg-blue-100/70 px-1.5 py-0.5 rounded">名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值</code>。
|
||||
类型填 text/data/image/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={downloadCardTemplate}
|
||||
className="px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors"
|
||||
>
|
||||
<FileDown className="w-4 h-4" />
|
||||
下载模板
|
||||
</button>
|
||||
<label className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors">
|
||||
<Upload className="w-4 h-4" />
|
||||
{batchFile ? batchFile.name : '选择 .xlsx / .csv / .tsv'}
|
||||
<input type="file" accept=".xlsx,.csv,.tsv" className="hidden" onChange={e => setBatchFile(e.target.files?.[0] || null)} />
|
||||
</label>
|
||||
</div>
|
||||
{batchResult && !batchResult.error && (
|
||||
<div className="rounded-xl border border-gray-200 p-4 space-y-2">
|
||||
<div className="text-sm font-bold text-gray-900">
|
||||
共 {batchResult.total} 行 · 成功 {batchResult.created} · 失败 {batchResult.failed}
|
||||
</div>
|
||||
{batchResult.failed > 0 && (
|
||||
<div className="max-h-48 overflow-y-auto space-y-1">
|
||||
{batchResult.rows.filter((r: any) => !r.success).map((r: any) => (
|
||||
<div key={r.row_no} className="text-xs text-red-600">第 {r.row_no} 行「{r.name}」:{r.error}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{dataCards.length === 0 ? (
|
||||
<div className="rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800">
|
||||
暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">选择卡密组</label>
|
||||
<select
|
||||
value={appendTargetId}
|
||||
onChange={e => setAppendTargetId(e.target.value)}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
>
|
||||
{dataCards.map(c => (
|
||||
<option key={c.id} value={String(c.id)}>{c.name}(ID: {c.id})</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">卡密号(每行一个)</label>
|
||||
<textarea
|
||||
value={appendContent}
|
||||
onChange={e => setAppendContent(e.target.value)}
|
||||
placeholder={'VIP-001\nVIP-002\nVIP-003'}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"
|
||||
/>
|
||||
<p className="text-xs text-gray-500">一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。</p>
|
||||
</div>
|
||||
{appendResult && (
|
||||
<div className="rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold">
|
||||
已追加 {appendResult.added} 个卡密
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3">
|
||||
<button
|
||||
onClick={() => setShowBatchModal(false)}
|
||||
className="px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors"
|
||||
>
|
||||
关闭
|
||||
</button>
|
||||
{batchTab === 'create' ? (
|
||||
<button
|
||||
onClick={handleBatchCreate}
|
||||
disabled={!batchFile || batchBusy}
|
||||
className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{batchBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}
|
||||
{batchBusy ? '处理中...' : '上传创建'}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={handleBatchAppend}
|
||||
disabled={!appendTargetId || !appendContent.trim() || batchBusy || dataCards.length === 0}
|
||||
className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{batchBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
|
||||
{batchBusy ? '处理中...' : '追加卡密'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -32,7 +32,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
};
|
||||
|
||||
const StatCard: React.FC<{ title: string; value: string | number; icon: React.ElementType; colorClass: string; trend?: string }> = ({ title, value, icon: Icon, colorClass, trend }) => (
|
||||
<div className="ios-card p-6 rounded-[2rem] flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0">
|
||||
<div className="ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0">
|
||||
<div className={`absolute -right-6 -top-6 w-32 h-32 ${colorClass} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}></div>
|
||||
<div className="flex justify-between items-start mb-6">
|
||||
<div className={`p-4 rounded-2xl ${colorClass} bg-opacity-10 backdrop-blur-sm`}>
|
||||
@@ -393,7 +393,7 @@ const Dashboard: React.FC = () => {
|
||||
</div>
|
||||
|
||||
{/* Main Chart Section */}
|
||||
<div className="ios-card p-8 rounded-[2rem]">
|
||||
<div className="ios-card p-8 rounded-xl">
|
||||
<div className="mb-10">
|
||||
<h3 className="text-xl font-bold text-gray-900">营收趋势分析</h3>
|
||||
<p className="text-sm text-gray-400 mt-1">{selectedRangeLabel}的销售额走势</p>
|
||||
@@ -425,7 +425,7 @@ const Dashboard: React.FC = () => {
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: '#fff',
|
||||
borderRadius: '16px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #e5e7eb',
|
||||
boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1)',
|
||||
padding: '12px 16px'
|
||||
@@ -478,7 +478,7 @@ const Dashboard: React.FC = () => {
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: '#fff',
|
||||
borderRadius: '16px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #e5e7eb',
|
||||
boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1)',
|
||||
padding: '12px 16px'
|
||||
@@ -497,7 +497,7 @@ const Dashboard: React.FC = () => {
|
||||
{/* 商品销量排行和订单来源分布 */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
{/* 商品销量排行 */}
|
||||
<div className="ios-card p-6 rounded-[2rem]">
|
||||
<div className="ios-card p-6 rounded-xl">
|
||||
<h3 className="font-bold text-lg text-gray-900 mb-6">商品销量排行</h3>
|
||||
<div className="h-[280px]">
|
||||
{productSalesData.length === 0 ? (
|
||||
@@ -529,7 +529,7 @@ const Dashboard: React.FC = () => {
|
||||
</div>
|
||||
|
||||
{/* 商品下单占比 */}
|
||||
<div className="ios-card p-6 rounded-[2rem]">
|
||||
<div className="ios-card p-6 rounded-xl">
|
||||
<h3 className="font-bold text-lg text-gray-900 mb-6">商品下单占比</h3>
|
||||
<div className="h-[280px]">
|
||||
{sourceDataData.length === 0 ? (
|
||||
@@ -568,7 +568,7 @@ const Dashboard: React.FC = () => {
|
||||
{/* 收支明细和品类营收 */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||
{/* 参与统计的订单列表 */}
|
||||
<div className="lg:col-span-2 ios-card p-0 rounded-[2rem] border-0 bg-white overflow-hidden flex flex-col">
|
||||
<div className="lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col">
|
||||
<div className="p-6 border-b border-gray-50 flex justify-between items-center bg-[#FAFAFA]">
|
||||
<h3 className="font-bold text-lg text-gray-900">参与统计的订单</h3>
|
||||
<div className="relative">
|
||||
@@ -670,7 +670,7 @@ const Dashboard: React.FC = () => {
|
||||
</div>
|
||||
|
||||
{/* 商品金额分析 */}
|
||||
<div className="ios-card p-6 rounded-[2rem] bg-white">
|
||||
<div className="ios-card p-6 rounded-xl bg-white">
|
||||
<h3 className="font-bold text-lg text-gray-900 mb-6">商品金额分析 (TOP5)</h3>
|
||||
{categoryDataData.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-[300px] text-gray-400">暂无数据</div>
|
||||
@@ -697,7 +697,7 @@ const Dashboard: React.FC = () => {
|
||||
contentStyle={{
|
||||
backgroundColor: '#fff',
|
||||
border: '1px solid #e5e7eb',
|
||||
borderRadius: '12px',
|
||||
borderRadius: '6px',
|
||||
boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
|
||||
}}
|
||||
formatter={(value: number) => `¥${value.toLocaleString()}`}
|
||||
|
||||
@@ -358,8 +358,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const downloadPublishTemplate = () => {
|
||||
const headers = [
|
||||
'账号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'],
|
||||
@@ -472,55 +472,55 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
|
||||
{items.map(item => {
|
||||
const linkedRules = rulesForItem(item);
|
||||
const hasRule = linkedRules.length > 0;
|
||||
return (
|
||||
<div key={`${item.cookie_id}-${item.item_id}`} className="ios-card p-4 rounded-3xl hover:shadow-lg transition-all group relative flex flex-col">
|
||||
<div className="absolute top-3 right-3 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10">
|
||||
<div key={`${item.cookie_id}-${item.item_id}`} className="ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col">
|
||||
<div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10">
|
||||
<button
|
||||
onClick={() => handleEdit(item)}
|
||||
className="p-2 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors"
|
||||
className="p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors"
|
||||
title="编辑"
|
||||
>
|
||||
<Edit className="w-4 h-4" />
|
||||
<Edit className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(item)}
|
||||
className="p-2 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors"
|
||||
className="p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors"
|
||||
title="删除"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="aspect-square bg-gray-100 rounded-2xl mb-4 overflow-hidden relative">
|
||||
<div className="aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative">
|
||||
{item.item_image ? (
|
||||
<img src={item.item_image} alt="" className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-gray-300">
|
||||
<Box className="w-10 h-10" />
|
||||
<Box className="w-8 h-8" />
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute top-2 left-2 bg-black/50 backdrop-blur-md text-white text-xs font-bold px-2 py-1 rounded-lg">
|
||||
<div className="absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md">
|
||||
{formatItemPrice(item.item_price)}
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="font-bold text-gray-900 line-clamp-2 text-sm mb-2 h-10">{item.item_title}</h3>
|
||||
<div className="flex justify-between items-center text-xs text-gray-500 mb-3">
|
||||
<span className="bg-gray-100 px-2 py-1 rounded-md truncate max-w-[100px]">ID: {item.item_id}</span>
|
||||
<h3 className="font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4">{item.item_title}</h3>
|
||||
<div className="flex justify-between items-center text-[10px] text-gray-500 mb-2">
|
||||
<span className="bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]">ID: {item.item_id}</span>
|
||||
<span className={`inline-flex items-center gap-1 font-bold ${hasRule ? 'text-emerald-600' : 'text-amber-600'}`}>
|
||||
{hasRule ? <CheckCircle2 className="w-3.5 h-3.5" /> : <CircleDashed className="w-3.5 h-3.5" />}
|
||||
{hasRule ? `${linkedRules.length} 条规则` : '未配置规则'}
|
||||
{hasRule ? <CheckCircle2 className="w-3 h-3" /> : <CircleDashed className="w-3 h-3" />}
|
||||
{hasRule ? `${linkedRules.length} 规则` : '未配置'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-2 mt-auto">
|
||||
<button
|
||||
onClick={() => onConfigureDelivery(item)}
|
||||
className={`w-full flex items-center justify-between gap-2 px-3 py-2.5 rounded-xl text-xs font-extrabold transition-all ${hasRule ? 'bg-gray-900 text-white hover:bg-black' : 'bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100'}`}
|
||||
className={`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${hasRule ? 'bg-gray-900 text-white hover:bg-black' : 'bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100'}`}
|
||||
>
|
||||
<span className="flex items-center gap-2"><Link2 className="w-4 h-4" />{hasRule ? '查看并编辑发货规则' : '关联自动发货规则'}</span>
|
||||
<ArrowRight className="w-4 h-4" />
|
||||
<span className="flex items-center gap-1.5"><Link2 className="w-3.5 h-3.5" />{hasRule ? '查看发货规则' : '关联发货规则'}</span>
|
||||
<ArrowRight className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { NotificationChannel, NotificationChannelType, SystemSettings } from '../types';
|
||||
import {
|
||||
getNotificationChannels,
|
||||
createNotificationChannel,
|
||||
updateNotificationChannel,
|
||||
deleteNotificationChannel,
|
||||
testNotificationChannel,
|
||||
getSystemSettings,
|
||||
updateSystemSettings,
|
||||
} from '../services/api';
|
||||
import {
|
||||
Bell, Plus, Edit2, Trash2, X, Send, RefreshCw, Loader2,
|
||||
Check, MessageCircle, Mail, Webhook, Send as Telegram, Eye, EyeOff, Save,
|
||||
} from 'lucide-react';
|
||||
|
||||
type ChannelTypeMeta = {
|
||||
label: string;
|
||||
icon: React.ElementType;
|
||||
fields: { key: string; label: string; placeholder?: string; type?: 'text' | 'password' | 'number'; required?: boolean; help?: string }[];
|
||||
guide: { steps: string[]; urlFormat?: string; note?: string };
|
||||
};
|
||||
|
||||
const CHANNEL_TYPES: Record<NotificationChannelType, ChannelTypeMeta> = {
|
||||
bark: {
|
||||
label: 'Bark',
|
||||
icon: Bell,
|
||||
fields: [
|
||||
{ key: 'server_url', label: 'Bark 服务器', placeholder: 'https://api.day.app', required: true },
|
||||
{ key: 'device_key', label: 'Device Key', placeholder: '你的 Bark 设备 Key', required: true },
|
||||
{ key: 'title', label: '标题(可选)', placeholder: '闲鱼助手' },
|
||||
{ key: 'sound', label: '铃声(可选)', placeholder: 'default' },
|
||||
{ key: 'group', label: '分组(可选)', placeholder: 'xianyu' },
|
||||
],
|
||||
guide: {
|
||||
steps: [
|
||||
'App Store 搜索并安装 Bark(免费)',
|
||||
'打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容',
|
||||
'URL 路径里 <key> 那一段就是 Device Key,复制填入',
|
||||
'服务器地址默认 https://api.day.app,自建服务端则填自建域名',
|
||||
],
|
||||
urlFormat: 'https://api.day.app/<你的key>/测试内容',
|
||||
note: '不需要 secret,Device Key 本身就是唯一凭证。',
|
||||
},
|
||||
},
|
||||
dingtalk: {
|
||||
label: '钉钉机器人',
|
||||
icon: MessageCircle,
|
||||
fields: [
|
||||
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://oapi.dingtalk.com/robot/send?access_token=...', required: true },
|
||||
{ key: 'secret', label: '加签密钥', placeholder: 'SEC...', help: '安全设置勾选「加签」后生成,SEC 开头' },
|
||||
],
|
||||
guide: {
|
||||
steps: [
|
||||
'钉钉进入一个群(可建单人群)→ 右上角 群设置',
|
||||
'机器人 → 添加机器人 → 选择「自定义机器人」',
|
||||
'安全设置勾选「加签」',
|
||||
'完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制',
|
||||
'Webhook URL 填上面,Secret 填加签密钥',
|
||||
],
|
||||
urlFormat: 'https://oapi.dingtalk.com/robot/send?access_token=XXX',
|
||||
note: '加签密钥可选,但强烈建议启用,否则机器人可能被滥用。',
|
||||
},
|
||||
},
|
||||
feishu: {
|
||||
label: '飞书机器人',
|
||||
icon: MessageCircle,
|
||||
fields: [
|
||||
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://open.feishu.cn/open-apis/bot/v2/hook/...', required: true },
|
||||
{ key: 'secret', label: '签名校验密钥', placeholder: 'sec-...', help: '安全设置选「签名校验」后生成' },
|
||||
],
|
||||
guide: {
|
||||
steps: [
|
||||
'飞书进入目标群 → 右上角 更多 → 设置',
|
||||
'群机器人 → 添加机器人 → 自定义机器人',
|
||||
'安全设置选择「签名校验」,复制生成的秘钥',
|
||||
'完成会给 Webhook 地址,复制',
|
||||
'Webhook URL 填上面,秘钥填签名校验密钥',
|
||||
],
|
||||
urlFormat: 'https://open.feishu.cn/open-apis/bot/v2/hook/xxx',
|
||||
note: '签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。',
|
||||
},
|
||||
},
|
||||
wechat: {
|
||||
label: '企业微信机器人',
|
||||
icon: MessageCircle,
|
||||
fields: [
|
||||
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...', required: true },
|
||||
],
|
||||
guide: {
|
||||
steps: [
|
||||
'企业微信进入一个内部群 → 右上角 … → 群设置',
|
||||
'找到「群机器人」(新版可能叫「消息推送」)',
|
||||
'添加 → 选择自定义机器人',
|
||||
'完成给 Webhook 地址(含 ?key=),复制填入',
|
||||
],
|
||||
urlFormat: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX',
|
||||
note: '不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。',
|
||||
},
|
||||
},
|
||||
webhook: {
|
||||
label: '自定义 Webhook',
|
||||
icon: Webhook,
|
||||
fields: [
|
||||
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://your-server/notify', required: true },
|
||||
],
|
||||
guide: {
|
||||
steps: [
|
||||
'仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON',
|
||||
'系统会 POST 这个 URL,Content-Type: application/json',
|
||||
'请求体固定为右侧 JSON 格式,按需解析 message 字段',
|
||||
],
|
||||
urlFormat: '{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',
|
||||
note: '若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。',
|
||||
},
|
||||
},
|
||||
telegram: {
|
||||
label: 'Telegram',
|
||||
icon: Telegram,
|
||||
fields: [
|
||||
{ key: 'bot_token', label: 'Bot Token', placeholder: '123456:ABC-DEF...', required: true },
|
||||
{ key: 'chat_id', label: 'Chat ID', placeholder: '-1001234567890 或你的用户 ID', required: true },
|
||||
],
|
||||
guide: {
|
||||
steps: [
|
||||
'在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token',
|
||||
'把你的 Bot 拉进一个群,或私聊它发一条消息',
|
||||
'浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates',
|
||||
'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)',
|
||||
],
|
||||
urlFormat: 'Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890',
|
||||
note: '群聊需先把 Bot 设为管理员才能发消息。',
|
||||
},
|
||||
},
|
||||
email: {
|
||||
label: '邮件',
|
||||
icon: Mail,
|
||||
fields: [
|
||||
{ key: 'smtp_server', label: 'SMTP 服务器', placeholder: 'smtp.qq.com', required: true },
|
||||
{ key: 'smtp_port', label: 'SMTP 端口', placeholder: '587', type: 'number', required: true },
|
||||
{ key: 'smtp_user', label: '发件邮箱', placeholder: 'you@qq.com', required: true },
|
||||
{ key: 'smtp_password', label: '密码 / 授权码', type: 'password', required: true },
|
||||
{ key: 'from', label: '收件邮箱(可选)', placeholder: '留空则发给自己' },
|
||||
],
|
||||
guide: {
|
||||
steps: [
|
||||
'QQ 邮箱:服务器 smtp.qq.com,端口 587,发件邮箱填你的 QQ 邮箱',
|
||||
'QQ 邮箱密码栏填「授权码」不是 QQ 密码:QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码',
|
||||
'163 邮箱:smtp.163.com:587,同样使用授权码',
|
||||
'Gmail:smtp.gmail.com:587,密码用「应用专用密码」',
|
||||
],
|
||||
note: '收件邮箱留空时,邮件会发到发件邮箱自己。',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const Notifications: React.FC = () => {
|
||||
const [channels, setChannels] = useState<NotificationChannel[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [editing, setEditing] = useState<NotificationChannel | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testingId, setTestingId] = useState<string>('');
|
||||
const [toast, setToast] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
|
||||
|
||||
// SMTP 系统级邮件配置(从系统设置加载/保存)
|
||||
const [smtp, setSmtp] = useState<SystemSettings>({});
|
||||
const [smtpSaving, setSmtpSaving] = useState(false);
|
||||
const [showSmtpPassword, setShowSmtpPassword] = useState(false);
|
||||
|
||||
const [form, setForm] = useState({
|
||||
name: '',
|
||||
type: 'bark' as NotificationChannelType,
|
||||
enabled: true,
|
||||
config: {} as Record<string, unknown>,
|
||||
});
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await getNotificationChannels();
|
||||
setChannels(res.data || []);
|
||||
} catch (e) {
|
||||
console.error('加载通知渠道失败', e);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadSmtp = async () => {
|
||||
try {
|
||||
const s = await getSystemSettings();
|
||||
setSmtp(s || {});
|
||||
} catch (e) {
|
||||
console.error('加载 SMTP 配置失败', e);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveSmtp = async () => {
|
||||
setSmtpSaving(true);
|
||||
try {
|
||||
await updateSystemSettings({
|
||||
smtp_server: smtp.smtp_server || '',
|
||||
smtp_port: smtp.smtp_port || 587,
|
||||
smtp_user: smtp.smtp_user || '',
|
||||
smtp_password: smtp.smtp_password || '',
|
||||
smtp_from: smtp.smtp_from || '',
|
||||
});
|
||||
showToast('success', 'SMTP 配置已保存');
|
||||
} catch (e: any) {
|
||||
showToast('error', e?.message || '保存失败');
|
||||
} finally {
|
||||
setSmtpSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { load(); loadSmtp(); }, []);
|
||||
|
||||
const showToast = (type: 'success' | 'error', text: string) => {
|
||||
setToast({ type, text });
|
||||
window.setTimeout(() => setToast(null), 3000);
|
||||
};
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm({ name: '', type: 'bark', enabled: true, config: {} });
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
const openEdit = (ch: NotificationChannel) => {
|
||||
setEditing(ch);
|
||||
setForm({
|
||||
name: ch.name,
|
||||
type: ch.type,
|
||||
enabled: ch.enabled,
|
||||
config: { ...(ch.config || {}) },
|
||||
});
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
const meta = CHANNEL_TYPES[form.type];
|
||||
for (const f of meta.fields) {
|
||||
if (f.required && !String(form.config[f.key] || '').trim()) {
|
||||
showToast('error', `请填写 ${f.label}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!form.name.trim()) {
|
||||
showToast('error', '请填写渠道名称');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = { name: form.name.trim(), type: form.type, config: form.config, enabled: form.enabled };
|
||||
if (editing) {
|
||||
await updateNotificationChannel(editing.id, payload);
|
||||
} else {
|
||||
await createNotificationChannel(payload);
|
||||
}
|
||||
setShowModal(false);
|
||||
await load();
|
||||
showToast('success', editing ? '已更新' : '已创建');
|
||||
} catch (e: any) {
|
||||
console.error('保存失败', e);
|
||||
showToast('error', e?.message || '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (ch: NotificationChannel) => {
|
||||
if (!confirm(`确认删除渠道「${ch.name}」吗?已绑定该渠道的账号会自动解绑。`)) return;
|
||||
try {
|
||||
await deleteNotificationChannel(ch.id);
|
||||
await load();
|
||||
showToast('success', '已删除');
|
||||
} catch (e: any) {
|
||||
showToast('error', e?.message || '删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleEnabled = async (ch: NotificationChannel) => {
|
||||
try {
|
||||
// 后端 updateChannel 是全量更新,必须把 name/type/config 一起发回去,
|
||||
// 否则会被空串覆盖并触发 type 的 CHECK 约束报"更新失败"。
|
||||
await updateNotificationChannel(ch.id, {
|
||||
name: ch.name,
|
||||
type: ch.type,
|
||||
config: ch.config || {},
|
||||
enabled: !ch.enabled,
|
||||
});
|
||||
setChannels(prev => prev.map(c => c.id === ch.id ? { ...c, enabled: !c.enabled } : c));
|
||||
} catch (e: any) {
|
||||
showToast('error', e?.message || '切换失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleTest = async (ch: NotificationChannel) => {
|
||||
setTestingId(ch.id);
|
||||
try {
|
||||
await testNotificationChannel(ch.id);
|
||||
showToast('success', '测试通知已发送,请检查对应渠道');
|
||||
} catch (e: any) {
|
||||
showToast('error', e?.message || '发送失败');
|
||||
} finally {
|
||||
setTestingId('');
|
||||
}
|
||||
};
|
||||
|
||||
const meta = CHANNEL_TYPES[form.type];
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-fade-in">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row justify-between md: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">配置通知渠道,账号异常时主动推送告警</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={load}
|
||||
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
刷新
|
||||
</button>
|
||||
<button
|
||||
onClick={openCreate}
|
||||
className="ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
新建渠道
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 说明 */}
|
||||
<div className="ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100">
|
||||
<div className="flex items-start gap-3">
|
||||
<Bell className="w-5 h-5 text-[#0094f7] mt-0.5 flex-shrink-0" />
|
||||
<div className="text-sm text-gray-700 leading-6">
|
||||
配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:
|
||||
<ul className="mt-2 space-y-1 text-gray-600">
|
||||
<li>• <strong>账号 session 失效</strong>:系统正在尝试自动恢复(警告)</li>
|
||||
<li>• <strong>自动恢复失败</strong>:账号已停止,需人工处理(严重)</li>
|
||||
<li>• <strong>触发风控验证</strong>:可能需要扫码完成验证(警告)</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 渠道列表 */}
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-20">
|
||||
<Loader2 className="w-8 h-8 text-[#0094f7] animate-spin" />
|
||||
</div>
|
||||
) : channels.length === 0 ? (
|
||||
<div className="ios-card rounded-xl p-12 bg-white text-center">
|
||||
<Bell className="w-12 h-12 text-gray-300 mx-auto mb-4" />
|
||||
<p className="text-gray-500 font-medium">还没有配置任何通知渠道</p>
|
||||
<p className="text-gray-400 text-sm mt-1">点击右上角「新建渠道」开始配置</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{channels.map(ch => {
|
||||
const tMeta = CHANNEL_TYPES[ch.type] || CHANNEL_TYPES.webhook;
|
||||
const Icon = tMeta.icon;
|
||||
return (
|
||||
<div key={ch.id} className="ios-card rounded-xl p-5 bg-white flex items-center gap-4">
|
||||
<div className="w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0">
|
||||
<Icon className="w-5 h-5 text-gray-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-bold text-gray-900 truncate">{ch.name}</span>
|
||||
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium">{tMeta.label}</span>
|
||||
{!ch.enabled && (
|
||||
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium">已停用</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 mt-1 truncate">
|
||||
{tMeta.fields.map(f => ch.config?.[f.key]).filter(Boolean).map((v, i) => (
|
||||
<span key={i} className="mr-3">{String(v).length > 40 ? String(v).slice(0, 40) + '…' : String(v)}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
<button
|
||||
onClick={() => handleToggleEnabled(ch)}
|
||||
className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${ch.enabled ? 'bg-green-50 text-green-700 hover:bg-green-100' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'}`}
|
||||
>
|
||||
{ch.enabled ? '启用中' : '已停用'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTest(ch)}
|
||||
disabled={testingId === ch.id}
|
||||
className="px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-[#0094f7] hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50"
|
||||
>
|
||||
{testingId === ch.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <Send className="w-3 h-3" />}
|
||||
测试
|
||||
</button>
|
||||
<button
|
||||
onClick={() => openEdit(ch)}
|
||||
className="w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors"
|
||||
title="编辑"
|
||||
>
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(ch)}
|
||||
className="w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors"
|
||||
title="删除"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* SMTP 邮件配置(系统级,用于注册验证码等邮件) */}
|
||||
<section className="ios-card rounded-xl p-6 bg-white space-y-5">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-extrabold text-gray-800">SMTP 邮件配置</h3>
|
||||
<p className="text-sm text-gray-500 mt-1">系统级邮件发送服务,用于注册验证码等邮件通知</p>
|
||||
</div>
|
||||
<div className="p-2 rounded-xl bg-blue-50 text-blue-600">
|
||||
<Mail className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">SMTP 服务器</label>
|
||||
<input
|
||||
type="text"
|
||||
value={smtp.smtp_server || ''}
|
||||
onChange={e => setSmtp({ ...smtp, smtp_server: e.target.value })}
|
||||
placeholder="smtp.qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">SMTP 端口</label>
|
||||
<input
|
||||
type="number"
|
||||
value={smtp.smtp_port || 587}
|
||||
onChange={e => setSmtp({ ...smtp, smtp_port: parseInt(e.target.value) || 587 })}
|
||||
placeholder="587"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">发件邮箱</label>
|
||||
<input
|
||||
type="email"
|
||||
value={smtp.smtp_user || ''}
|
||||
onChange={e => setSmtp({ ...smtp, smtp_user: e.target.value })}
|
||||
placeholder="your-email@qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">邮箱密码 / 授权码</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showSmtpPassword ? 'text' : 'password'}
|
||||
value={smtp.smtp_password || ''}
|
||||
onChange={e => setSmtp({ ...smtp, smtp_password: e.target.value })}
|
||||
placeholder="输入密码或授权码"
|
||||
className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSmtpPassword(!showSmtpPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors"
|
||||
>
|
||||
{showSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={smtp.smtp_from || ''}
|
||||
onChange={e => setSmtp({ ...smtp, smtp_from: e.target.value })}
|
||||
placeholder="闲鱼自动回复系统"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSaveSmtp}
|
||||
disabled={smtpSaving}
|
||||
className="ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{smtpSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{smtpSaving ? '保存中...' : '保存 SMTP 配置'}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
{/* 新建/编辑弹窗 */}
|
||||
{showModal && createPortal(
|
||||
<div className="modal-overlay">
|
||||
<div className="modal-container" style={{ maxWidth: '36rem' }}>
|
||||
<div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between">
|
||||
<h3 className="text-xl font-extrabold text-gray-900">{editing ? '编辑通知渠道' : '新建通知渠道'}</h3>
|
||||
<button
|
||||
onClick={() => setShowModal(false)}
|
||||
className="w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-600" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">渠道名称</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.name}
|
||||
onChange={e => setForm({ ...form, name: e.target.value })}
|
||||
placeholder="例如:我的 Bark"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">渠道类型</label>
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{(Object.keys(CHANNEL_TYPES) as NotificationChannelType[]).map(t => {
|
||||
const m = CHANNEL_TYPES[t];
|
||||
const TIcon = m.icon;
|
||||
const selected = form.type === t;
|
||||
return (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
onClick={() => setForm({ ...form, type: t, config: {} })}
|
||||
className={`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${selected ? 'border-[#0094f7] bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
|
||||
>
|
||||
<TIcon className={`w-5 h-5 ${selected ? 'text-[#0094f7]' : 'text-gray-500'}`} />
|
||||
<span className={`text-xs font-bold ${selected ? 'text-[#0094f7]' : 'text-gray-600'}`}>{m.label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 配置指南:选中类型后显示对应获取步骤 */}
|
||||
<div className="rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Bell className="w-4 h-4 text-amber-600" />
|
||||
<span className="text-sm font-bold text-amber-800">如何获取 {meta.label} 配置?</span>
|
||||
</div>
|
||||
<ol className="space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5">
|
||||
{meta.guide.steps.map((step, i) => (
|
||||
<li key={i}>{step}</li>
|
||||
))}
|
||||
</ol>
|
||||
{meta.guide.urlFormat && (
|
||||
<div className="text-xs text-amber-900/90">
|
||||
<span className="font-bold">格式示例:</span>
|
||||
<code className="mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]">{meta.guide.urlFormat}</code>
|
||||
</div>
|
||||
)}
|
||||
{meta.guide.note && (
|
||||
<p className="text-xs text-amber-800/80 leading-5 pt-1">💡 {meta.guide.note}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{meta.fields.map(f => (
|
||||
<div key={f.key} className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">
|
||||
{f.label}
|
||||
{f.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<input
|
||||
type={f.type === 'password' ? 'password' : f.type === 'number' ? 'number' : 'text'}
|
||||
value={String(form.config[f.key] || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, [f.key]: e.target.value } })}
|
||||
placeholder={f.placeholder}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
{f.help && <p className="text-xs text-gray-500">{f.help}</p>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-3 cursor-pointer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setForm({ ...form, enabled: !form.enabled })}
|
||||
className={`relative w-11 h-6 rounded-full transition-colors ${form.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
|
||||
>
|
||||
<span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${form.enabled ? 'translate-x-5' : ''}`} />
|
||||
</button>
|
||||
<span className="text-sm font-bold text-gray-800">启用此渠道</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3">
|
||||
<button
|
||||
onClick={() => setShowModal(false)}
|
||||
className="px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
|
||||
{saving ? '保存中...' : '保存'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
|
||||
{/* Toast */}
|
||||
{toast && (
|
||||
<div className="fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in"
|
||||
style={{ background: toast.type === 'success' ? '#10b981' : '#ef4444', color: 'white' }}>
|
||||
{toast.type === 'success' ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
|
||||
{toast.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Notifications;
|
||||
@@ -339,7 +339,7 @@ const OrderList: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ios-card rounded-[2rem] overflow-hidden shadow-lg border-0 bg-white">
|
||||
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
|
||||
{/* Toolbar */}
|
||||
<div className="p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-[#FAFAFA]">
|
||||
<div className="flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full">
|
||||
|
||||
@@ -682,101 +682,69 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
: '编辑默认回复';
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-fade-in pb-20">
|
||||
<div className="relative overflow-hidden rounded-[2rem] bg-[#101827] text-white p-8 shadow-2xl">
|
||||
<div className="absolute -right-20 -top-20 h-64 w-64 rounded-full bg-[#0094f7]/30 blur-3xl" />
|
||||
<div className="absolute right-32 bottom-0 h-32 w-32 rounded-full bg-emerald-400/20 blur-2xl" />
|
||||
<div className="relative flex flex-col lg:flex-row lg:items-end justify-between gap-6">
|
||||
<div>
|
||||
<div className="inline-flex items-center gap-2 rounded-full bg-white/10 px-3 py-1 text-xs font-bold text-blue-100 mb-4">
|
||||
<Zap className="w-3.5 h-3.5" />
|
||||
自动化中心
|
||||
</div>
|
||||
<h2 className="text-4xl font-black tracking-tight">自动化规则</h2>
|
||||
<p className="text-blue-100/80 mt-3 max-w-2xl leading-7">
|
||||
系统通知卡片只进入自动化判断;买家用户消息才进入关键词、默认回复或 AI 回复。
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3 min-w-[360px]">
|
||||
{triggerOrder.map(trigger => {
|
||||
const meta = triggerMeta[trigger];
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
<button
|
||||
key={trigger}
|
||||
onClick={() => openNewAutomationRule(trigger)}
|
||||
className="rounded-2xl bg-white/10 hover:bg-white/15 border border-white/10 p-4 text-left transition-colors"
|
||||
>
|
||||
<Icon className="w-5 h-5 text-white mb-3" />
|
||||
<div className="text-sm font-extrabold">{meta.shortLabel}</div>
|
||||
<div className="text-[11px] text-blue-100/70 mt-1">{rulesByTrigger[trigger].length} 条规则</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="space-y-8 animate-fade-in">
|
||||
<div className="flex flex-col md:flex-row justify-between md: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">
|
||||
<select
|
||||
value={selectedAccountId}
|
||||
onChange={event => setSelectedAccountId(event.target.value)}
|
||||
className="ios-input px-4 py-3 rounded-2xl text-sm min-w-64"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountLabel(account)}</option>
|
||||
))}
|
||||
</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"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
刷新
|
||||
</button>
|
||||
<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"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
{primaryActionLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="sticky top-0 z-40 -mx-8 md:-mx-12 px-8 md:px-12 py-3 bg-[#F4F5F7] shadow-[0_18px_34px_rgba(244,245,247,0.96)]">
|
||||
<div className="flex flex-col xl:flex-row xl:items-center justify-between gap-4 rounded-3xl bg-white p-3 shadow-sm border border-gray-100">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[
|
||||
{ id: 'automation' as const, label: '交易自动化', icon: Zap },
|
||||
{ id: 'reply' as const, label: '关键词回复', icon: MessageCircle },
|
||||
{ id: 'default' as const, label: '账号默认回复', icon: Bot },
|
||||
].map(tab => {
|
||||
const Icon = tab.icon;
|
||||
return (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`inline-flex items-center gap-2 px-5 py-3 rounded-2xl text-sm font-extrabold transition-all ${
|
||||
activeTab === tab.id
|
||||
? 'bg-gray-900 text-white shadow-lg'
|
||||
: 'text-gray-500 hover:text-gray-900 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
{tab.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<select
|
||||
value={selectedAccountId}
|
||||
onChange={event => setSelectedAccountId(event.target.value)}
|
||||
className="ios-input px-4 py-3 rounded-2xl text-sm min-w-64"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountLabel(account)}</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl">
|
||||
{[
|
||||
{ id: 'automation' as const, label: '交易自动化', icon: Zap },
|
||||
{ id: 'reply' as const, label: '关键词回复', icon: MessageCircle },
|
||||
{ id: 'default' as const, label: '账号默认回复', icon: Bot },
|
||||
].map(tab => {
|
||||
const Icon = tab.icon;
|
||||
return (
|
||||
<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"
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${
|
||||
activeTab === tab.id
|
||||
? 'bg-[#0094f7] text-white shadow-md'
|
||||
: 'bg-white text-gray-600 hover:text-black hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
刷新
|
||||
<Icon className="w-4 h-4" />
|
||||
{tab.label}
|
||||
</button>
|
||||
<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"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
{primaryActionLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{activeTab === 'automation' && (
|
||||
<div className="grid grid-cols-1 2xl:grid-cols-[360px_1fr] gap-6">
|
||||
<aside className="space-y-4">
|
||||
<div className="bg-white rounded-[2rem] p-5 border border-gray-100 shadow-sm">
|
||||
<div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm">
|
||||
<h3 className="font-black text-gray-900 mb-1">新建规则</h3>
|
||||
<p className="text-sm text-gray-500 mb-4">先选自动化类型,再配置对应动作。</p>
|
||||
<div className="space-y-3">
|
||||
@@ -805,7 +773,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-[2rem] p-5 border border-gray-100 shadow-sm">
|
||||
<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="space-y-3">
|
||||
{triggerOrder.map(trigger => {
|
||||
@@ -827,7 +795,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
|
||||
<section className="space-y-4">
|
||||
{visibleAutomationRules.length === 0 ? (
|
||||
<div className="bg-white rounded-[2rem] border border-dashed border-gray-200 p-16 text-center">
|
||||
<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>
|
||||
@@ -837,7 +805,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
const meta = triggerMeta[rule.trigger_type];
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
<article key={rule.id} className="bg-white rounded-[2rem] border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all">
|
||||
<article key={rule.id} className="bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all">
|
||||
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
|
||||
<div className="flex items-start gap-4 min-w-0">
|
||||
<div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${accentClasses(meta.accent, true)}`}>
|
||||
@@ -890,7 +858,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
)}
|
||||
|
||||
{activeTab === 'reply' && (
|
||||
<section className="bg-white rounded-[2rem] border border-gray-100 p-6 shadow-sm">
|
||||
<section className="bg-white rounded-xl border border-gray-100 p-6 shadow-sm">
|
||||
<div className="flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit">
|
||||
<AlertCircle className="w-4 h-4" />
|
||||
这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。
|
||||
@@ -930,7 +898,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
)}
|
||||
|
||||
{activeTab === 'default' && (
|
||||
<section className="bg-white rounded-[2rem] border border-gray-100 p-6 shadow-sm">
|
||||
<section className="bg-white rounded-xl border border-gray-100 p-6 shadow-sm">
|
||||
<div className="flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit">
|
||||
<AlertCircle className="w-4 h-4" />
|
||||
默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from '../services/api';
|
||||
import { SystemSettings } from '../types';
|
||||
import {
|
||||
Save, Sparkles, Mail, Settings as SettingsIcon,
|
||||
Save, Sparkles, Settings as SettingsIcon,
|
||||
Eye, EyeOff, RefreshCw, Database, ChevronDown, Check,
|
||||
LockKeyhole, UserRound, ShieldCheck
|
||||
} from 'lucide-react';
|
||||
@@ -27,7 +27,6 @@ const Settings: React.FC = () => {
|
||||
|
||||
// Password visibility states
|
||||
const [showApiKey, setShowApiKey] = useState(false);
|
||||
const [showSmtpPassword, setShowSmtpPassword] = useState(false);
|
||||
const [showCurrentPassword, setShowCurrentPassword] = useState(false);
|
||||
const [showNewPassword, setShowNewPassword] = useState(false);
|
||||
const [credentialsSaving, setCredentialsSaving] = useState(false);
|
||||
@@ -93,7 +92,9 @@ const Settings: React.FC = () => {
|
||||
if(!settings) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateSystemSettings(settings);
|
||||
// SMTP 字段已移至「通知设置」页面,这里不保存,避免覆盖那边已存的值。
|
||||
const { smtp_server, smtp_port, smtp_user, smtp_password, smtp_from, ...rest } = settings;
|
||||
await updateSystemSettings(rest);
|
||||
alert('系统配置已保存');
|
||||
} catch (e) {
|
||||
alert('保存失败:' + (e as Error).message);
|
||||
@@ -181,7 +182,7 @@ const Settings: React.FC = () => {
|
||||
基础设置
|
||||
</h3>
|
||||
|
||||
<div className="ios-card rounded-[2rem] p-6 bg-white space-y-4">
|
||||
<div className="ios-card rounded-xl p-6 bg-white space-y-4">
|
||||
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
|
||||
<div>
|
||||
<div className="font-bold text-gray-900">允许用户注册</div>
|
||||
@@ -298,7 +299,7 @@ const Settings: React.FC = () => {
|
||||
AI 智能回复配置
|
||||
</h3>
|
||||
|
||||
<div className="ios-card rounded-[2rem] p-6 bg-white space-y-6">
|
||||
<div className="ios-card rounded-xl p-6 bg-white space-y-6">
|
||||
<div className="space-y-3">
|
||||
<label className="block text-sm font-bold text-gray-800">API 地址</label>
|
||||
<input
|
||||
@@ -431,7 +432,7 @@ const Settings: React.FC = () => {
|
||||
登录凭据
|
||||
</h3>
|
||||
|
||||
<form onSubmit={handleCredentialsSave} className="ios-card rounded-[2rem] p-6 bg-white space-y-5">
|
||||
<form onSubmit={handleCredentialsSave} className="ios-card rounded-xl p-6 bg-white space-y-5">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">登录用户名</label>
|
||||
<div className="relative">
|
||||
@@ -511,85 +512,7 @@ const Settings: React.FC = () => {
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{/* SMTP Settings */}
|
||||
<section className="space-y-4">
|
||||
<h3 className="text-lg font-extrabold text-gray-800 flex items-center gap-2">
|
||||
<div className="p-1.5 rounded-lg bg-blue-100 text-blue-600">
|
||||
<Mail className="w-4 h-4" />
|
||||
</div>
|
||||
SMTP 邮件配置
|
||||
</h3>
|
||||
|
||||
<div className="ios-card rounded-[2rem] p-6 bg-white space-y-6">
|
||||
<p className="text-sm text-gray-500">配置SMTP服务器用于发送注册验证码等邮件通知</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-3">
|
||||
<label className="block text-sm font-bold text-gray-800">SMTP服务器</label>
|
||||
<input
|
||||
type="text"
|
||||
value={settings.smtp_server || ''}
|
||||
onChange={e => setSettings({...settings, smtp_server: e.target.value})}
|
||||
placeholder="smtp.qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<label className="block text-sm font-bold text-gray-800">SMTP端口</label>
|
||||
<input
|
||||
type="number"
|
||||
value={settings.smtp_port || 587}
|
||||
onChange={e => setSettings({...settings, smtp_port: parseInt(e.target.value)})}
|
||||
placeholder="587"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<label className="block text-sm font-bold text-gray-800">发件邮箱</label>
|
||||
<input
|
||||
type="email"
|
||||
value={settings.smtp_user || ''}
|
||||
onChange={e => setSettings({...settings, smtp_user: e.target.value})}
|
||||
placeholder="your-email@qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<label className="block text-sm font-bold text-gray-800">邮箱密码/授权码</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showSmtpPassword ? 'text' : 'password'}
|
||||
value={settings.smtp_password || ''}
|
||||
onChange={e => setSettings({...settings, smtp_password: e.target.value})}
|
||||
placeholder="输入密码或授权码"
|
||||
className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSmtpPassword(!showSmtpPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors"
|
||||
>
|
||||
{showSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">QQ邮箱需要使用授权码</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={settings.smtp_from || ''}
|
||||
onChange={e => setSettings({...settings, smtp_from: e.target.value})}
|
||||
placeholder="闲鱼自动回复系统"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{/* SMTP 配置已移至「通知设置」页面 */}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -598,7 +521,7 @@ const Settings: React.FC = () => {
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="ios-btn-primary px-10 py-5 rounded-[2rem] text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70"
|
||||
className="ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70"
|
||||
>
|
||||
<Save className="w-6 h-6" />
|
||||
{saving ? '保存中...' : '保存所有配置'}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import React from 'react';
|
||||
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap } from 'lucide-react';
|
||||
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap, Bell } from 'lucide-react';
|
||||
|
||||
interface SidebarProps {
|
||||
activeTab: string;
|
||||
setActiveTab: (tab: string) => void;
|
||||
onNavigate: (tab: string) => void;
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
const Sidebar: React.FC<SidebarProps> = ({ activeTab, setActiveTab, onLogout }) => {
|
||||
const Sidebar: React.FC<SidebarProps> = ({ activeTab, onNavigate, onLogout }) => {
|
||||
const menuItems = [
|
||||
{ id: 'dashboard', icon: LayoutDashboard, label: '仪表盘' },
|
||||
{ id: 'accounts', icon: Users, label: '账号管理' },
|
||||
@@ -15,6 +15,7 @@ const Sidebar: React.FC<SidebarProps> = ({ activeTab, setActiveTab, onLogout })
|
||||
{ id: 'cards', icon: CreditCard, label: '卡密库存' },
|
||||
{ id: 'items', icon: Box, label: '商品列表' },
|
||||
{ id: 'rules', icon: Zap, label: '自动化规则' },
|
||||
{ id: 'notifications', icon: Bell, label: '通知设置' },
|
||||
{ id: 'settings', icon: Settings, label: '系统与AI' },
|
||||
];
|
||||
|
||||
@@ -35,7 +36,7 @@ const Sidebar: React.FC<SidebarProps> = ({ activeTab, setActiveTab, onLogout })
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => setActiveTab(item.id)}
|
||||
onClick={() => onNavigate(item.id)}
|
||||
className={`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${
|
||||
isActive
|
||||
? 'bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]'
|
||||
|
||||
+5
-5
@@ -43,7 +43,7 @@ body {
|
||||
/* 闲鱼风格卡片 */
|
||||
.ios-card {
|
||||
background: #FFFFFF;
|
||||
border-radius: 24px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(0, 0, 0, 0.02);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||
@@ -300,7 +300,7 @@ body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: white;
|
||||
border-radius: 2.5rem;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -355,7 +355,7 @@ body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: white;
|
||||
border-radius: 2.5rem;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -363,7 +363,7 @@ body {
|
||||
/* 响应式工具类 */
|
||||
@media (max-width: 768px) {
|
||||
.ios-card {
|
||||
border-radius: 16px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.ios-input {
|
||||
@@ -373,7 +373,7 @@ body {
|
||||
.modal-container {
|
||||
max-width: calc(100% - 2rem);
|
||||
max-height: 90vh;
|
||||
border-radius: 1.5rem;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.modal-header,
|
||||
|
||||
@@ -308,6 +308,24 @@ export const getCardDetails = async (cardId: string | number): Promise<any> => {
|
||||
return normalizeCard(card);
|
||||
};
|
||||
|
||||
// 批量创建卡密组(上传表格)
|
||||
export const batchCreateCards = async (file: File): Promise<{
|
||||
success: boolean;
|
||||
total: number;
|
||||
created: number;
|
||||
failed: number;
|
||||
rows: { row_no: number; success: boolean; id?: number; name: string; type?: string; error?: string }[];
|
||||
}> => {
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
return postForm('/cards/batch', body);
|
||||
};
|
||||
|
||||
// 往 data 类型卡密组批量追加卡密号
|
||||
export const appendCardData = async (cardId: string | number, content: string): Promise<{ success: boolean; added: number }> => {
|
||||
return post(`/cards/${cardId}/append-data`, { content });
|
||||
};
|
||||
|
||||
// Items
|
||||
const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
value === true || value === 1 || value === '1';
|
||||
@@ -638,7 +656,7 @@ export const createNotificationChannel = async (data: { name: string; type: stri
|
||||
});
|
||||
}
|
||||
|
||||
export const updateNotificationChannel = async (channelId: string, data: { name?: string; config?: Record<string, unknown>; enabled?: boolean }): Promise<ApiResponse> => {
|
||||
export const updateNotificationChannel = async (channelId: string, data: { name?: string; type?: string; config?: Record<string, unknown>; enabled?: boolean }): Promise<ApiResponse> => {
|
||||
const payload: Record<string, unknown> = { ...data };
|
||||
if ('config' in data) {
|
||||
payload.config = JSON.stringify(data.config);
|
||||
@@ -681,6 +699,21 @@ export const deleteAccountNotifications = async (cookieId: string): Promise<ApiR
|
||||
return del(`/message-notifications/account/${cookieId}`);
|
||||
}
|
||||
|
||||
// 账号 ↔ 渠道 绑定(覆盖式)
|
||||
export const getAccountBindings = async (cookieId: string): Promise<number[]> => {
|
||||
const result = await get<{ cookie_id: string; channel_ids: number[] }>(`/message-notifications/${cookieId}`);
|
||||
return result?.channel_ids || [];
|
||||
}
|
||||
|
||||
export const setAccountBindings = async (cookieId: string, channelIds: number[]): Promise<ApiResponse> => {
|
||||
return post(`/message-notifications/${cookieId}`, { channel_ids: channelIds });
|
||||
}
|
||||
|
||||
// 测试发送
|
||||
export const testNotificationChannel = async (channelId: string): Promise<ApiResponse> => {
|
||||
return post(`/notification-channels/${channelId}/test`, {});
|
||||
}
|
||||
|
||||
// Default Reply
|
||||
export const getDefaultReplies = async (): Promise<Record<string, DefaultReply>> => {
|
||||
return get('/api/default-replies');
|
||||
|
||||
@@ -21,9 +21,16 @@ export default {
|
||||
canvas: '#fbfbfd', // 页面背景
|
||||
surface: '#f5f5f7', // 卡片背景/区块
|
||||
},
|
||||
// 圆角统一收紧到 5–10px 区间,UI 更紧凑、信息密度更高。
|
||||
borderRadius: {
|
||||
'2xl': '1.5rem',
|
||||
'3xl': '2rem',
|
||||
'none': '0px',
|
||||
'sm': '5px',
|
||||
DEFAULT: '6px',
|
||||
'md': '6px',
|
||||
'lg': '7px',
|
||||
'xl': '8px',
|
||||
'2xl': '10px',
|
||||
'3xl': '10px',
|
||||
},
|
||||
fontFamily: {
|
||||
sans: [
|
||||
|
||||
@@ -241,3 +241,16 @@ export interface DefaultReply {
|
||||
reply_once: boolean;
|
||||
reply_image_url?: string;
|
||||
}
|
||||
|
||||
// 通知渠道
|
||||
export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email';
|
||||
|
||||
export interface NotificationChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
type: NotificationChannelType;
|
||||
config: Record<string, unknown>;
|
||||
enabled: boolean;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
@@ -16,6 +16,7 @@ type noopHandler struct{}
|
||||
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
|
||||
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
|
||||
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
|
||||
func (noopHandler) OnAccountAlert(context.Context, string, string, string, string) {}
|
||||
|
||||
// TestManagerStartStop 验证从 DB 加载账号、启停和 GetInstance。
|
||||
// 用无效 cookie 让账号快速进入重连等待(不会真正连上),验证管理逻辑而非网络。
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ItemInfo 对应 item_info 表。
|
||||
@@ -131,6 +132,38 @@ func (c *Cards) ConsumeBatchData(ctx context.Context, cardID int64) (string, err
|
||||
return content, nil
|
||||
}
|
||||
|
||||
// AppendBatchData 往 data 类型卡密组追加卡密号(按行)。返回新增的有效(非空)行数。
|
||||
// 已有 data_content 非空时在末尾换行追加,否则直接写入。
|
||||
func (c *Cards) AppendBatchData(ctx context.Context, cardID int64, content string) (int, error) {
|
||||
lines := splitLines(content)
|
||||
valid := 0
|
||||
for _, l := range lines {
|
||||
if strings.TrimSpace(l) != "" {
|
||||
valid++
|
||||
}
|
||||
}
|
||||
if valid == 0 {
|
||||
return 0, errors.New("无有效卡密行")
|
||||
}
|
||||
var existing sql.NullString
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(&existing)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
merged := content
|
||||
if existing.Valid && existing.String != "" {
|
||||
merged = existing.String + "\n" + content
|
||||
}
|
||||
if _, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cards SET data_content=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`, merged, cardID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return valid, nil
|
||||
}
|
||||
|
||||
// splitLines / joinLines 统一处理多行库存内容。
|
||||
func splitLines(s string) []string {
|
||||
var out []string
|
||||
|
||||
+20
-6
@@ -118,12 +118,12 @@ func (i *ItemReplies) AllForUser(ctx context.Context, cookieID string) ([]ItemRe
|
||||
|
||||
// NotificationChannelRow 通知渠道完整行(含 id)。
|
||||
type NotificationChannelRow struct {
|
||||
ID int64
|
||||
Name string
|
||||
Type string
|
||||
Config string
|
||||
Enabled bool
|
||||
UserID int64
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// AllChannelsForUser 取某用户全部通知渠道。
|
||||
@@ -173,6 +173,20 @@ func (n *Notifications) DeleteChannel(ctx context.Context, id int64) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// GetChannel 按 ID 取单个通知渠道(含 config)。未找到返回 nil。
|
||||
func (n *Notifications) GetChannel(ctx context.Context, id int64) (*NotificationChannel, error) {
|
||||
row := n.DB.QueryRowContext(ctx,
|
||||
`SELECT id, name, type, config FROM notification_channels WHERE id=?`, id)
|
||||
var c NotificationChannel
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// AccountBindings 取某账号已绑定的通知渠道 ID 列表。
|
||||
func (n *Notifications) AccountBindings(ctx context.Context, cookieID string) ([]int64, error) {
|
||||
rows, err := n.DB.QueryContext(ctx,
|
||||
|
||||
@@ -28,12 +28,22 @@ const (
|
||||
MessageExpireTime = time.Hour // 去重有效期
|
||||
ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理
|
||||
HeartbeatInterval = 15 * time.Second
|
||||
TokenRefreshInterval = 1 * time.Hour
|
||||
// token 心跳间隔。主动刷新 token 让服务端持续续期 cookie(_m_h5_tk /
|
||||
// sgcookie 等),避免 cookie 自然滑向过期。15 分钟一次,平衡保活与风控。
|
||||
// 不宜过短,否则易触发阿里系滑块风控。
|
||||
TokenRefreshInterval = 15 * time.Minute
|
||||
TokenRefreshMinGap = time.Minute
|
||||
MessageCooldown = 5 * time.Minute // 收到消息后 5 分钟内不刷 cookie
|
||||
PasswordLoginMinGap = 30 * time.Minute
|
||||
)
|
||||
|
||||
// 告警级别(OnAccountAlert 的 level 参数)。
|
||||
const (
|
||||
AlertLevelInfo = "info"
|
||||
AlertLevelWarn = "warn"
|
||||
AlertLevelCritical = "critical"
|
||||
)
|
||||
|
||||
// Handler 是业务逻辑注入点(Phase 3 实现)。
|
||||
// 收到一条防抖后的聊天消息时回调;返回错误仅记录日志、不影响主循环。
|
||||
// 注:生产 handlerAdapter.HandleChatMessage 当前为 no-op,留作未来注入聊天旁路处理
|
||||
@@ -45,6 +55,9 @@ type Handler interface {
|
||||
HandleSystemEvent(ctx context.Context, task automation.Task) error
|
||||
// OnPasswordLoginRefresh 连续失败时触发浏览器密码登录刷新;返回是否成功。
|
||||
OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool
|
||||
// OnAccountAlert 账号告警通知(token 失效/自动恢复失败/风控验证等)。
|
||||
// level 取 AlertLevel* 常量。实现方应把告警推送到该账号绑定的通知渠道。
|
||||
OnAccountAlert(ctx context.Context, cookieID, level, title, body string)
|
||||
}
|
||||
|
||||
// ChatMessage 防抖后投递给业务层的一条聊天消息。
|
||||
@@ -195,7 +208,8 @@ func (a *Account) Run(parent context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 1) 刷新 token。
|
||||
// 1) 刷新 token。若服务端返回 session 过期,直接跳到密码登录刷新,
|
||||
// 不再空跑 5 次冷却重试。
|
||||
token, cookieStr, err := a.refreshToken(ctx)
|
||||
if err != nil {
|
||||
a.logger.Error("刷新 token 失败", "err", err)
|
||||
@@ -203,7 +217,16 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.connFailures++
|
||||
failures := a.connFailures
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeError(err)
|
||||
a.setRuntimeError(ctx, err)
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
a.logger.Warn("session 已失效,直接触发密码登录刷新", "err", err)
|
||||
a.alert(ctx, AlertLevelWarn, "账号 session 已失效",
|
||||
"登录凭证已被闲鱼服务端判定为失效,系统正在尝试通过浏览器密码登录自动恢复。若长时间未恢复,请人工处理。")
|
||||
if err := a.handleMaxFailures(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if failures >= MaxConnectionFailures {
|
||||
if err := a.handleMaxFailures(ctx); err != nil {
|
||||
return err
|
||||
@@ -220,6 +243,7 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.CookieStr = cookieStr
|
||||
a.connFailures = 0
|
||||
a.mu.Unlock()
|
||||
a.logger.Info("token 刷新成功")
|
||||
a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务")
|
||||
|
||||
// 2) 连接 WS + 注册。
|
||||
@@ -269,7 +293,7 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
|
||||
|
||||
// 3) 心跳 + 消息接收。
|
||||
// 3) 心跳 + 消息接收,并并行运行 token 定时刷新。
|
||||
hbCtx, hbCancel := context.WithCancel(ctx)
|
||||
var hbErr error
|
||||
go func() {
|
||||
@@ -277,8 +301,15 @@ func (a *Account) Run(parent context.Context) error {
|
||||
hbCancel()
|
||||
}()
|
||||
|
||||
refreshDone := make(chan struct{})
|
||||
go func() {
|
||||
a.tokenRefreshLoop(hbCtx, conn)
|
||||
close(refreshDone)
|
||||
}()
|
||||
|
||||
recvErr := conn.ReceiveLoop(ctx, a.dispatch)
|
||||
hbCancel()
|
||||
<-refreshDone
|
||||
_ = conn.Close()
|
||||
|
||||
// 连接结束:清 token,统计失败,决定重连或密码刷新。
|
||||
@@ -361,9 +392,19 @@ func (a *Account) handleMaxFailures(ctx context.Context) error {
|
||||
}
|
||||
a.resetFailures()
|
||||
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录")
|
||||
a.alert(ctx, AlertLevelCritical, "账号自动恢复失败,需人工处理",
|
||||
fmt.Sprintf("账号 %s 连续失败 %d 次,浏览器密码登录刷新未能恢复登录凭证,账号已停止运行。请前往后台重新扫码授权或检查账号用户名/密码配置。", a.CookieID, MaxConnectionFailures))
|
||||
return fmt.Errorf("账号 %s 连续失败 %d 次且密码登录刷新失败,需重启实例", a.CookieID, MaxConnectionFailures)
|
||||
}
|
||||
|
||||
// alert 触发账号告警通知。handler 未注入或为 nil 时静默跳过。
|
||||
func (a *Account) alert(ctx context.Context, level, title, body string) {
|
||||
if a.handler == nil {
|
||||
return
|
||||
}
|
||||
a.handler.OnAccountAlert(ctx, a.CookieID, level, title, body)
|
||||
}
|
||||
|
||||
func (a *Account) resetFailures() {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
@@ -448,6 +489,39 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
|
||||
return res.AccessToken, cookieStr, nil
|
||||
}
|
||||
|
||||
// tokenRefreshLoop 在 WS 在线期间按 TokenRefreshInterval 定时刷新 token。
|
||||
// 刷新失败不重连(让心跳/接收循环去判定),仅记录日志;session 过期会触发
|
||||
// 接收循环断开,主循环再走 handleMaxFailures 兜底。
|
||||
func (a *Account) tokenRefreshLoop(ctx context.Context, conn *ws.Conn) {
|
||||
ticker := time.NewTicker(TokenRefreshInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
token, _, err := a.refreshToken(ctx)
|
||||
if err != nil {
|
||||
a.logger.Warn("定时刷新 token 失败", "err", err)
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
// session 失效:让接收循环尽快断开走兜底,主动关闭连接。
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.currentToken = token
|
||||
a.mu.Unlock()
|
||||
conn.SetAccessToken(token)
|
||||
a.logger.Info("定时刷新 token 成功")
|
||||
}
|
||||
}
|
||||
|
||||
// RuntimeStatus 返回账号当前连接状态的线程安全快照。
|
||||
func (a *Account) RuntimeStatus() RuntimeStatus {
|
||||
a.mu.Lock()
|
||||
@@ -469,11 +543,17 @@ func (a *Account) setRuntimeState(state, message string) {
|
||||
a.runtimeUpdatedAt = time.Now()
|
||||
}
|
||||
|
||||
func (a *Account) setRuntimeError(err error) {
|
||||
func (a *Account) setRuntimeError(ctx context.Context, err error) {
|
||||
msg := strings.ToLower(errString(err))
|
||||
prev := a.runtimeState
|
||||
switch {
|
||||
case strings.Contains(msg, "验证"), strings.Contains(msg, "captcha"), strings.Contains(msg, "risk"), strings.Contains(msg, "rgv587"), strings.Contains(msg, "fail_sys_user_validate"):
|
||||
a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证,请重新扫码并完成验证")
|
||||
// 仅在从非验证状态转入时告警一次,避免重复刷屏。
|
||||
if prev != RuntimeVerificationRequired {
|
||||
a.alert(ctx, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
"账号触发闲鱼风控验证(滑块/短信/人脸等)。系统可能无法自动恢复,请前往后台扫码完成验证。")
|
||||
}
|
||||
case strings.Contains(msg, "登录凭证已失效"), strings.Contains(msg, "fail_sys_token_exoired"), strings.Contains(msg, "fail_sys_token_expired"), strings.Contains(msg, "cookie 缺少 unb"):
|
||||
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录")
|
||||
default:
|
||||
|
||||
@@ -38,6 +38,7 @@ func (h *recordingHandler) OnPasswordLoginRefresh(_ context.Context, _ string) b
|
||||
h.refresh++
|
||||
return true
|
||||
}
|
||||
func (h *recordingHandler) OnAccountAlert(_ context.Context, _, _, _, _ string) {}
|
||||
|
||||
func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, func()) {
|
||||
t.Helper()
|
||||
@@ -305,13 +306,13 @@ func TestRuntimeStatusClassifiesAuthenticationFailures(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
|
||||
acc.setRuntimeError(fmt.Errorf("token API 登录凭证已失效: FAIL_SYS_TOKEN_EXOIRED"))
|
||||
acc.setRuntimeError(context.Background(), fmt.Errorf("token API 登录凭证已失效: FAIL_SYS_TOKEN_EXOIRED"))
|
||||
status := acc.RuntimeStatus()
|
||||
if status.State != RuntimeAuthExpired || status.Connected {
|
||||
t.Fatalf("status=%+v", status)
|
||||
}
|
||||
|
||||
acc.setRuntimeError(fmt.Errorf("FAIL_SYS_USER_VALIDATE: captcha required"))
|
||||
acc.setRuntimeError(context.Background(), fmt.Errorf("FAIL_SYS_USER_VALIDATE: captcha required"))
|
||||
status = acc.RuntimeStatus()
|
||||
if status.State != RuntimeVerificationRequired {
|
||||
t.Fatalf("status=%+v", status)
|
||||
|
||||
@@ -60,6 +60,53 @@ func (n *Notifier) NotifyDelivery(accountID, buyerName, buyerID, itemID, message
|
||||
}
|
||||
}
|
||||
|
||||
// NotifyAccountAlert 发送账号告警通知(token 失效/自动恢复失败/风控验证等)。
|
||||
// level 取 AlertLevel* 常量。向该账号所有已启用渠道发送。
|
||||
func (n *Notifier) NotifyAccountAlert(accountID, level, title, body string) {
|
||||
if n.store == nil {
|
||||
return
|
||||
}
|
||||
channels, err := n.store.Notifications.AccountChannels(context.Background(), accountID)
|
||||
if err != nil || len(channels) == 0 {
|
||||
return
|
||||
}
|
||||
full := fmt.Sprintf("🚨 [%s] %s\n\n账号: %s\n时间: %s\n\n%s",
|
||||
levelLabel(level), title, accountID, time.Now().Format("2006-01-02 15:04:05"), body)
|
||||
for _, ch := range channels {
|
||||
if err := n.send(ch, full); err != nil {
|
||||
n.logger.Error("发送告警通知失败", "channel", ch.Type, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SendToChannel 直接向指定渠道发送一条消息(用于前端“测试发送”)。
|
||||
func (n *Notifier) SendToChannel(channelID int64, body string) error {
|
||||
if n.store == nil {
|
||||
return fmt.Errorf("通知器未初始化")
|
||||
}
|
||||
ch, err := n.store.Notifications.GetChannel(context.Background(), channelID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询渠道失败: %w", err)
|
||||
}
|
||||
if ch == nil {
|
||||
return fmt.Errorf("渠道不存在")
|
||||
}
|
||||
return n.send(*ch, body)
|
||||
}
|
||||
|
||||
func levelLabel(level string) string {
|
||||
switch level {
|
||||
case "critical":
|
||||
return "严重"
|
||||
case "warn":
|
||||
return "警告"
|
||||
case "info":
|
||||
return "提示"
|
||||
default:
|
||||
return level
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Notifier) send(ch db.NotificationChannel, message string) error {
|
||||
cfg := parseConfig(ch.Config)
|
||||
switch ch.Type {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
const maxCardBatchRows = 200
|
||||
|
||||
type cardBatchResultRow struct {
|
||||
RowNo int `json:"row_no"`
|
||||
Success bool `json:"success"`
|
||||
ID int64 `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// batchCreateCards 上传表格批量创建卡密组。每行一个组定义。
|
||||
func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// 表格最大 5 MiB(卡密组定义都很小)。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 6<<20)
|
||||
if err := r.ParseMultipartForm(6 << 20); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "解析上传文件失败")
|
||||
return
|
||||
}
|
||||
source, sourceHeader, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "缺少卡密表格文件")
|
||||
return
|
||||
}
|
||||
defer source.Close()
|
||||
sourceBytes, err := io.ReadAll(io.LimitReader(source, 5<<20))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "读取卡密表格失败")
|
||||
return
|
||||
}
|
||||
sourceName := safeBaseName(sourceHeader.Filename)
|
||||
if sourceName == "" {
|
||||
sourceName = "cards.csv"
|
||||
}
|
||||
maps, err := parsePublishSheetBytes(sourceBytes, sourceName)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if len(maps) > maxCardBatchRows {
|
||||
writeErr(w, http.StatusBadRequest, fmt.Sprintf("单次最多创建 %d 个卡密组", maxCardBatchRows))
|
||||
return
|
||||
}
|
||||
|
||||
results := make([]cardBatchResultRow, 0, len(maps))
|
||||
created, failed := 0, 0
|
||||
for i, m := range maps {
|
||||
rowNo := i + 2
|
||||
name := strings.TrimSpace(firstImportString(m, "name", "名称", "卡密组名称", "卡密名称"))
|
||||
cardType := strings.ToLower(strings.TrimSpace(firstImportString(m, "type", "类型", "卡密类型")))
|
||||
content := firstImportString(m, "content", "内容", "卡密内容")
|
||||
|
||||
// 校验
|
||||
if name == "" {
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "缺少名称"})
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
switch cardType {
|
||||
case "text", "data", "image", "api":
|
||||
default:
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "类型必须为 text/data/image/api"})
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
// content 按类型映射;api 类型允许 content 为空(用 description 等另行说明时)
|
||||
if cardType != "api" && strings.TrimSpace(content) == "" {
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "缺少内容"})
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
cf := &db.CardFull{
|
||||
Name: name,
|
||||
Type: cardType,
|
||||
Description: firstImportString(m, "description", "描述"),
|
||||
Enabled: true,
|
||||
DelaySeconds: atoiPublishDefault(firstImportString(m, "delay_seconds", "延迟秒"), 0),
|
||||
IsMultiSpec: parseLooseBool(firstImportString(m, "is_multi_spec", "多规格")),
|
||||
SpecName: firstImportString(m, "spec_name", "规格名"),
|
||||
SpecValue: firstImportString(m, "spec_value", "规格值"),
|
||||
UserID: sess.UserID,
|
||||
}
|
||||
if v := firstImportString(m, "enabled", "启用"); v != "" {
|
||||
cf.Enabled = parseLooseBool(v)
|
||||
}
|
||||
switch cardType {
|
||||
case "text":
|
||||
cf.TextContent = content
|
||||
case "data":
|
||||
cf.DataContent = content
|
||||
case "image":
|
||||
cf.ImageURL = content
|
||||
case "api":
|
||||
cf.APIConfig = content
|
||||
}
|
||||
|
||||
id, err := s.Store.Cards.Create(r.Context(), cf)
|
||||
if err != nil {
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "创建失败: " + err.Error()})
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: true, ID: id, Name: name, Type: cardType})
|
||||
created++
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"total": len(maps),
|
||||
"created": created,
|
||||
"failed": failed,
|
||||
"rows": results,
|
||||
})
|
||||
}
|
||||
|
||||
// appendCardData 往 data 类型卡密组追加卡密号(按行)。
|
||||
func (s *Server) appendCardData(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "无效卡券ID")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
content := strings.TrimSpace(req.Content)
|
||||
if content == "" {
|
||||
writeErr(w, http.StatusBadRequest, "内容为空")
|
||||
return
|
||||
}
|
||||
cf, err := s.Store.Cards.Get(r.Context(), id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "卡券不存在")
|
||||
return
|
||||
}
|
||||
if cf.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该卡密组")
|
||||
return
|
||||
}
|
||||
if cf.Type != "data" {
|
||||
writeErr(w, http.StatusBadRequest, "只有 data(批量卡密)类型支持追加卡密")
|
||||
return
|
||||
}
|
||||
added, err := s.Store.Cards.AppendBatchData(r.Context(), id, content)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "追加失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "added": added})
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
func (s *Server) mountCardsReal(r chi.Router) {
|
||||
r.Get("/cards", s.listCards)
|
||||
r.Post("/cards", s.createCard)
|
||||
r.Post("/cards/batch", s.batchCreateCards)
|
||||
r.Post("/cards/{card_id}/append-data", s.appendCardData)
|
||||
r.Get("/cards/{card_id}/details", s.getCard)
|
||||
r.Get("/cards/{card_id}", s.getCard)
|
||||
r.Put("/cards/{card_id}", s.updateCard)
|
||||
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
@@ -15,6 +16,7 @@ func (s *Server) mountNotificationsReal(r chi.Router) {
|
||||
r.Post("/notification-channels", s.createChannel)
|
||||
r.Put("/notification-channels/{channel_id}", s.updateChannel)
|
||||
r.Delete("/notification-channels/{channel_id}", s.deleteChannel)
|
||||
r.Post("/notification-channels/{channel_id}/test", s.testChannel)
|
||||
r.Get("/message-notifications", s.listMessageNotifications)
|
||||
r.Delete("/message-notifications/account/{cid}", s.deleteAccountNotifications)
|
||||
r.Delete("/message-notifications/{notification_id}", s.deleteMessageNotification)
|
||||
@@ -92,6 +94,26 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
// testChannel 向指定渠道发送一条测试通知,便于用户验证配置是否正确。
|
||||
func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
if s.Notifier == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "通知器未启用")
|
||||
return
|
||||
}
|
||||
body := "🧪 通知渠道测试\n\n这是一条来自闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: " +
|
||||
time.Now().Format("2006-01-02 15:04:05")
|
||||
if err := s.Notifier.SendToChannel(id, body); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "发送失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
ids, err := s.Store.Notifications.AccountBindings(r.Context(), cid)
|
||||
|
||||
@@ -56,6 +56,7 @@ type noopHandler struct{}
|
||||
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
|
||||
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
|
||||
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
|
||||
func (noopHandler) OnAccountAlert(context.Context, string, string, string, string) {}
|
||||
|
||||
// TestLoginVerifyLogout 登录→verify→登出 全链路。
|
||||
func TestLoginVerifyLogout(t *testing.T) {
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
|
||||
<script type="module" crossorigin src="/static/assets/index-yhnDCVg7.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-jAhq_csJ.css">
|
||||
<script type="module" crossorigin src="/static/assets/index-ukRBmZzU.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-D_KvwSmE.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -677,13 +677,27 @@ func hasMTopSuccess(ret []string) bool {
|
||||
func isTokenExpiredRet(ret []string) bool {
|
||||
for _, r := range ret {
|
||||
lower := strings.ToLower(r)
|
||||
if strings.Contains(lower, "token") || strings.Contains(r, "FAIL_SYS_TOKEN_EXOIRED") || strings.Contains(r, "FAIL_SYS_TOKEN_EXPIRED") {
|
||||
if strings.Contains(lower, "token") ||
|
||||
strings.Contains(r, "FAIL_SYS_TOKEN_EXOIRED") ||
|
||||
strings.Contains(r, "FAIL_SYS_TOKEN_EXPIRED") ||
|
||||
strings.Contains(r, "FAIL_SYS_SESSION_EXPIRED") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsSessionExpiredErr 判断错误是否表示 cookie/session 已彻底失效(需密码登录刷新)。
|
||||
func IsSessionExpiredErr(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "fail_sys_session_expired") ||
|
||||
strings.Contains(msg, "session过期") ||
|
||||
strings.Contains(msg, "登录凭证已失效")
|
||||
}
|
||||
|
||||
func mtopString(v any) string {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
|
||||
@@ -348,13 +348,23 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
case "NEW":
|
||||
// 未扫码,继续
|
||||
case "EXPIRED":
|
||||
// 验证中的 EXPIRED 是正常的(验证通过后二维码 session 结束),
|
||||
// 保持 verification_required 状态,等用户点"我已完成验证"。
|
||||
if sess.Status != "verification_required" {
|
||||
// 浏览器自动验证可能已把状态置为 success:二维码 session 结束是
|
||||
// 验证通过后的正常现象,此时绝不能把 success 覆盖回 expired,
|
||||
// 否则前端轮询会错过自动完成的登录、不存 cookie、不重启账号。
|
||||
m.mu.Lock()
|
||||
curStatus := sess.Status
|
||||
if curStatus == "success" {
|
||||
m.mu.Unlock()
|
||||
m.logger.Info("验证已自动完成,二维码 session 结束", "session_id", sessionID)
|
||||
return
|
||||
}
|
||||
if curStatus != "verification_required" {
|
||||
sess.Status = "expired"
|
||||
m.mu.Unlock()
|
||||
m.logger.Info("二维码已过期", "session_id", sessionID)
|
||||
return
|
||||
}
|
||||
m.mu.Unlock()
|
||||
m.logger.Info("验证中收到 EXPIRED,保持验证状态", "session_id", sessionID)
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
|
||||
@@ -312,6 +312,13 @@ func (c *Conn) sendJSON(ctx context.Context, v any) error {
|
||||
return c.ws.Write(ctx, websocket.MessageText, b)
|
||||
}
|
||||
|
||||
// SetAccessToken 在线更新 token(仅在连接保持期间用于定时刷新)。
|
||||
func (c *Conn) SetAccessToken(token string) {
|
||||
c.sendMu.Lock()
|
||||
defer c.sendMu.Unlock()
|
||||
c.cfg.AccessToken = token
|
||||
}
|
||||
|
||||
// SendText 发送一条闲鱼聊天文本消息。
|
||||
func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error {
|
||||
content := map[string]any{
|
||||
|
||||
Reference in new issue
Block a user