Compare commits

...
Author SHA1 Message Date
Christ 526ac44453 fix: 完善同步生命周期并统一前端视觉
- 同步商品与订单时处理线上删除状态并联动自动化规则\n- 过滤卖家系统中的购买订单,修复订单逻辑删除与数据库迁移\n- 修复聊天新消息自动滚动,并统一前端颜色令牌与硬编码颜色检查
2026-08-10 12:41:10 +08:00
Christ cf76b8898b merge: 合并商品同步与逻辑删除修复 2026-08-10 11:24:37 +08:00
Christ 9adc77df73 fix(商品同步): 修复全量同步删除与规则生命周期 2026-08-10 11:21:35 +08:00
Christ 4fb857da1e merge: 合并商品同步修复到 main 2026-08-10 01:11:56 +08:00
Christ 182cc75e63 fix(商品同步): 完善线上商品全量同步 2026-08-10 01:11:45 +08:00
Christ 450a62c924 修复自动化规则统计口径
- 新增按筛选条件聚合的规则触发类型统计\n- 修复分页数据导致分类数量与规则总数不一致的问题\n- 补充前后端统计接口测试并同步嵌入式前端资源
2026-08-09 00:10:24 +08:00
Christ fe3f715cdc feat: 完善聊天识别与规则页面响应式布局
- 按闲鱼协议字段识别官方系统消息、交易卡片和闲小蜜,清理空会话壳并补齐历史消息校正\n- 同步 README、项目展示页和 GitHub Wiki,补充在线聊天、账号自动评价与每日擦亮说明\n- 优化自动化规则页面的中等宽度布局,补充前端类型、响应式测试和嵌入资源
2026-08-08 23:48:42 +08:00
Christ 4d1f58c5ec merge: promote phase1 chat and account automation 2026-08-08 22:42:14 +08:00
Christ 0de1ec7635 merge: integrate phase1 chat and account automation 2026-08-08 22:19:36 +08:00
76 changed files with 1766 additions and 371 deletions

No files matched your search

+14 -4
View File
@@ -13,7 +13,7 @@
[Docker 部署](#docker-部署) · [开发指南](#开发指南) · [开源协议](#开源协议)
操作手册见仓库内的 [GitHub Wiki 文档](docs/wiki/Home.md):包含数据库选择、账号接入、
批量铺货、自动化发货、AI、通知和运维流程。
在线聊天、账号自动任务、批量铺货、自动化发货、AI、通知和运维流程。
> [!IMPORTANT]
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或
@@ -57,8 +57,9 @@ Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名
| --- | --- |
| 账号管理 | 多账号启停、扫码登录、密码登录、资料刷新、在线状态、登录审计与备注管理 |
| 凭证续期 | Cookie/token 定时续期、WebSocket 凭证更新、失效恢复、冷却与失败停用 |
| 即时消息 | 闲鱼 WebSocket 长连接、消息收发、关键词回复、默认回复及仅回复一次 |
| 即时消息 | 按账号隔离的在线聊天、会话列表与历史消息、闲鱼表情、文本/图片收发、官方系统消息识别、关键词回复、默认回复及仅回复一次 |
| 自动化中心 | 付款后自动发货、评价后赠品、超时未评价提醒、失败任务恢复与幂等检查点 |
| 账号自动任务 | 账号级持续扫描待评价订单并统一好评、按北京时间每日擦亮、手动立即执行、执行记录与幂等保护 |
| 卡密库存 | 文本、批量卡密和图片三种交付类型,库存追加、批量导入、规格与延迟发送 |
| 商品管理 | 商品同步、手工关联、单商品发布、CSV + ZIP 批量铺货、关键词获取默认类目、逐行类目优先、自动识别与“电子资料”最终兜底、任务恢复与结果导出 |
| 订单管理 | 订单同步、插入、编辑、平台发货、补发卡密、仅确认发货及异常状态处理 |
@@ -97,7 +98,13 @@ flowchart LR
## 页面预览
![Ydisks闲鱼助手预览](https://raw.githubusercontent.com/Christ9038/Ydisks-Xianyu-Helper/main/docs/img/preview.png)
![Ydisks闲鱼助手预览](https://raw.githubusercontent.com/Christ9038/Ydisks-Xianyu-Helper/main/docs/img/preview_account.png)
![Ydisks闲鱼助手预览](https://raw.githubusercontent.com/Christ9038/Ydisks-Xianyu-Helper/main/docs/img/preview_im.png)
![Ydisks闲鱼助手预览](https://raw.githubusercontent.com/Christ9038/Ydisks-Xianyu-Helper/main/docs/img/preview_auto.png)
## 快速开始
@@ -203,7 +210,9 @@ go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser
4. 等待账号状态变为在线,再同步商品和订单。
5. 在“卡密库存”创建交付内容。
6. 在“自动化规则”将闲鱼商品与卡密、规格和触发条件关联。
7. 按需配置关键词回复、默认回复、AI 回复和通知渠道。
7. 在“在线聊天”按账号查看历史会话、发送文本/表情/图片;官方交易卡片和闲小蜜消息会以系统消息显示,不会进入普通用户回复链。
8. 在“账号管理 → 自动评价与每日擦亮”按账号配置统一评价文案、评价开关和擦亮时间;确认测试账号行为后再启用。
9. 按需配置关键词回复、默认回复、AI 回复和通知渠道。
扫码登录是推荐方式。密码登录适合已有明确需求的环境,但更容易触发平台安全校验。
无论使用哪种方式,都不要把 Cookie、密码、二维码或人脸验证地址分享给不可信第三方。
@@ -290,6 +299,7 @@ DATABASE_URL="postgres://user:pass@127.0.0.1:5432/xianyu?sslmode=disable" ./xian
以下配置通过 Web 管理后台维护并保存在数据库中:
- **账号设置**:启停状态、备注、通知渠道绑定和单账号 AI 回复策略
- **账号自动任务**:自动评价开关、统一好评文案(最多 500 个字符)、每日擦亮开关、北京时间执行时间和最近执行记录
- **自动化规则**:触发条件、商品、规格、卡密组、发送数量、延迟和后续动作
- **回复规则**:关键词、文本或图片回复、默认回复及回复次数限制
- **AI 设置**:OpenAI 兼容 API 地址、API Key、模型和全局提示词
+65 -24
View File
@@ -55,78 +55,119 @@ func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writ
}
if existing != nil {
fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username)
fmt.Fprint(out, "是否重置管理员密码?(y/N): ")
if _, err := fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username); err != nil {
return err
}
if _, err := fmt.Fprint(out, "是否重置管理员密码?(y/N): "); err != nil {
return err
}
ans, _ := reader.ReadString('\n')
if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") {
fmt.Fprintln(out, "跳过初始化")
if _, err := fmt.Fprintln(out, "跳过初始化"); err != nil {
return err
}
return nil
}
pw := promptPasswordTwice(reader, out)
pw, err := promptPasswordTwice(reader, out)
if err != nil {
return fmt.Errorf("读取密码失败: %w", err)
}
if _, err := auth.InitAdmin(ctx, store, "", pw); err != nil {
return fmt.Errorf("重置 admin 密码失败: %w", err)
}
fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username)
if _, err := fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username); err != nil {
return err
}
return nil
}
fmt.Fprintln(out, "=== 初始化管理员账号(CLI)===")
fmt.Fprint(out, "请输入管理员邮箱: ")
if _, err := fmt.Fprintln(out, "=== 初始化管理员账号(CLI)==="); err != nil {
return err
}
if _, err := fmt.Fprint(out, "请输入管理员邮箱: "); err != nil {
return err
}
email, _ := reader.ReadString('\n')
email = strings.TrimSpace(email)
if email == "" {
return errors.New("邮箱不能为空")
}
pw := promptPasswordTwice(reader, out)
pw, err := promptPasswordTwice(reader, out)
if err != nil {
return fmt.Errorf("读取密码失败: %w", err)
}
created, err := auth.InitAdmin(ctx, store, email, pw)
if err != nil {
return fmt.Errorf("创建 admin 用户失败:%w", err)
}
if created {
fmt.Fprintln(out, "初始化完成:已创建 admin 用户")
if _, err := fmt.Fprintln(out, "初始化完成:已创建 admin 用户"); err != nil {
return err
}
}
return nil
}
// promptPasswordTwice 两次输入密码(不回显)并校验一致性。
func promptPasswordTwice(reader *bufio.Reader, out io.Writer) string {
func promptPasswordTwice(reader *bufio.Reader, out io.Writer) (string, error) {
for {
p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out)
p1, err := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out)
if err != nil {
return "", err
}
if p1 == "" {
fmt.Fprintln(out, "密码不能为空")
if _, err := fmt.Fprintln(out, "密码不能为空"); err != nil {
return "", err
}
continue
}
p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out)
p2, err := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out)
if err != nil {
return "", err
}
if p1 != p2 {
fmt.Fprintln(out, "两次输入不一致,请重试")
if _, err := fmt.Fprintln(out, "两次输入不一致,请重试"); err != nil {
return "", err
}
continue
}
return p1
return p1, nil
}
}
// readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道),
// 共用同一 bufio.Reader 避免缓冲吞掉后续输入。
func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) string {
fmt.Fprint(out, prompt)
func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) (string, error) {
if _, err := fmt.Fprint(out, prompt); err != nil {
return "", err
}
if term.IsTerminal(int(os.Stdin.Fd())) {
b, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(out)
if err != nil {
fatalf("读取密码失败: %v", err)
return "", err
}
return strings.TrimSpace(string(b))
if _, err := fmt.Fprintln(out); err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
}
// 非 TTY 回退:共用传入的 reader。
s, _ := reader.ReadString('\n')
fmt.Println()
return strings.TrimSpace(s)
s, err := reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
return "", err
}
if _, err := fmt.Fprintln(out); err != nil {
return "", err
}
return strings.TrimSpace(s), nil
}
func isNotFound(err error) bool { return errors.Is(err, db.ErrNotFound) }
func fatalf(format string, a ...any) {
fmt.Fprintf(os.Stderr, format+"\n", a...)
if _, err := fmt.Fprintf(os.Stderr, format+"\n", a...); err != nil {
os.Exit(1)
}
os.Exit(1)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 494 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 379 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 473 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 728 KiB

+9 -3
View File
@@ -4,12 +4,12 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ydisks闲鱼助手 - 基于 Go 与 React 构建的闲鱼多账号管理与自动发货系统</title>
<meta name="description" content="Ydisks闲鱼助手是一个面向闲鱼卖家的自托管管理系统。整合多账号登录、WebSocket即时消息、卡密库存交付、AI智能客服、自动化规则与多渠道告警。">
<meta name="description" content="Ydisks闲鱼助手是一个面向闲鱼卖家的自托管管理系统。整合多账号登录、按账号隔离的在线聊天、账号自动评价与每日擦亮、卡密库存交付、AI智能客服、自动化规则与多渠道告警。">
<meta name="keywords" content="闲鱼助手, 闲鱼自动发货, 闲鱼多账号管理, 闲鱼自动回复, 闲鱼AI客服, 闲鱼卡密发货, Go, React, Ydisks">
<!-- Open Graph -->
<meta property="og:title" content="Ydisks闲鱼助手 - 闲鱼多账号管理与自动发货系统">
<meta property="og:description" content="基于 Go 1.26 + React 19 构建的闲鱼自托管管理后台。自动化发货、AI回复、即时消息与风控续期。">
<meta property="og:description" content="基于 Go 1.26 + React 19 构建的闲鱼自托管管理后台。在线聊天、账号自动评价与每日擦亮、自动化发货、AI回复与风控续期。">
<meta property="og:type" content="website">
<meta property="og:image" content="img/slogan.png">
@@ -976,7 +976,7 @@
<div class="feature-card">
<div class="feature-icon-box">💬</div>
<h3 class="feature-card-title">WebSocket 即时消息处理</h3>
<p class="feature-card-desc">内置 Go 原生闲鱼 WebSocket 长连接通道,实时接收与推送聊天消息,支持关键词回复、默认回复及单次回复控制。</p>
<p class="feature-card-desc">按账号隔离在线聊天、历史消息和实时同步,支持闲鱼表情、文本/图片收发,并识别交易卡片与闲小蜜系统消息;普通消息继续支持关键词、默认回复及单次回复控制。</p>
</div>
<!-- Card 3 -->
@@ -986,6 +986,12 @@
<p class="feature-card-desc">自动关联买家付款事件,支持付款即发货、评价后赠品发放、超时提醒评价,内置幂等检查点防止重复发送。</p>
</div>
<div class="feature-card">
<div class="feature-icon-box">✨</div>
<h3 class="feature-card-title">账号自动评价与每日擦亮</h3>
<p class="feature-card-desc">按账号持续扫描待评价订单并使用统一文案评价;每日擦亮按北京时间执行,每个账号每天最多一次,并支持手动执行与结果记录。</p>
</div>
<!-- Card 4 -->
<div class="feature-card">
<div class="feature-icon-box">📦</div>
+4 -1
View File
@@ -1,4 +1,7 @@
# 登录续期与风控能力补齐计划
# 登录续期与风控能力实施记录
> 本文最初是实施计划。当前列出的五个阶段均已落地;后续协议变化应以实际代码、测试和
> 本文的实施记录为准,不应把“目标流程”误读为尚未实现的功能。
## 目标
+8 -5
View File
@@ -1,6 +1,7 @@
# Ydisks闲鱼助手 Wiki
本 Wiki 面向管理后台操作人员。先完成“部署与数据库”和“账号接入”,再配置库存、商品、自动化与 AI。
本 Wiki 面向管理后台操作人员。先完成“部署与数据库”和“账号接入”,再配置库存、商品、
在线聊天、账号自动任务、交易自动化与 AI。
## 推荐上线路径
@@ -9,15 +10,17 @@
3. 在“账号管理”扫码接入账号,确认账号为启用且在线状态。
4. 在“卡密库存”建立可交付内容。
5. 同步已有商品,或通过“商品管理”发布商品。
6. 在“自动化规则”建立付款发货、评价赠品或求评价规则。
7. 可选:在“系统与 AI”配置模型,再为每个账号启用 AI。
8. 建立通知渠道并绑定到账号;用测试通知验证。
9. 用小额测试订单验证“卡密发送 → 确认发货”全过程后,再开放正式商品。
6. 在“在线聊天”确认账号会话和历史消息正常,必要时发送测试文本或图片。
7. 在“账号自动任务”配置自动评价和每日擦亮;在“自动化规则”建立付款发货、评价赠品或求评价规则。
8. 可选:在“系统与 AI”配置模型,再为每个账号启用 AI。
9. 建立通知渠道并绑定到账号;用测试通知验证。
10. 用小额测试订单验证“卡密发送 → 确认发货”全过程后,再开放正式商品。
## 先读这些页面
- [部署与数据库](部署与数据库)
- [账号、库存与商品](账号、库存与商品)
- [在线聊天与账号自动任务](在线聊天与账号自动任务)
- [批量铺货](批量铺货)
- [自动化发货与回复](自动化发货与回复)
- [AI、通知与运维](AI、通知与运维)
+1
View File
@@ -3,6 +3,7 @@
- [首页](Home)
- [部署与数据库](部署与数据库)
- [账号、库存与商品](账号、库存与商品)
- [在线聊天与账号自动任务](在线聊天与账号自动任务)
- [批量铺货](批量铺货)
- [自动化发货与回复](自动化发货与回复)
- [AI、通知与运维](AI、通知与运维)
@@ -0,0 +1,62 @@
# 在线聊天与账号自动任务
## 在线聊天
进入“在线聊天”后,顶部按账号显示 Tab;每个账号拥有独立的会话列表和消息状态。下方是标准两栏布局:左侧为会话列表,右侧为当前会话消息窗口。
聊天功能包括:
- 会话联系人、头像、昵称、用户 ID、商品摘要和未读数;列表按闲鱼会话最后消息时间倒序。
- 进入会话后优先读取本地缓存,再从闲鱼历史消息接口补齐记录;底部可继续加载更早消息和更多历史联系人。
- 文本消息、闲鱼文字表情和图片发送。当前不支持从管理后台发送视频,因此界面不提供视频发送按钮。
- 发送方按“对方/我”区分,并显示对应头像;账号之间的会话和实时消息完全隔离。
- 应用使用后端 `/api/chat/ws` 推送实时事件;刷新或重连后仍以历史接口和本地数据库为准,不只依赖 WebSocket 存续期间收到的消息。
### 官方消息识别
闲鱼的交易卡片和平台通知不能当作普通用户消息处理。当前按协议元数据识别:
- `contentType=14`:平台通知类消息;
- `contentType=26`:交易卡片;
- 发送方用户 ID `1400`:闲小蜜;
- “发来一条新消息”:官方通知占位内容。
识别出的消息不会进入关键词、默认回复或 AI 回复链,并在聊天窗口中以居中的系统消息卡片展示。联系人分页返回的空会话壳不会导入列表,避免出现只有“暂无消息”的伪联系人。
如果昵称或头像缺失,点击会话列表刷新按钮;系统联系人闲小蜜使用平台头像和固定名称,不应把订单卡片标题当成用户昵称。
## 账号自动评价
入口为“账号管理 → 自动评价与每日擦亮”。自动评价是账号级开关,不针对不同买家配置不同文案:
1. 开启“自动评价”;
2. 填写统一好评文案,最多 500 个字符;
3. 保存后,后台持续扫描该账号的待评价订单;
4. 每个待评价订单按交易订单 ID 幂等执行,已经处理过的订单不会重复评价。
它不是每日任务。可以点击“立即评价”执行一次扫描,也可以依赖后台持续扫描。账号停用或暂停时不会执行。
## 每日自动擦亮
每日擦亮同样是账号级开关,但与自动评价不同:
- 按北京时间判断执行时间;
- 每个账号每天最多执行一次;
- 默认执行时间为 `03:00`,可在 `HH:mm` 范围内调整;
- 后台调用商品列表接口并逐个执行擦亮;当前实现按每页 20 条、最多 20 页读取商品;
- 可以点击“立即擦亮”手动触发,但当天已成功执行时会被幂等保护跳过;
- 页面会显示最近完成时间、本次发现数量、成功数、失败数和跳过数。
如果执行中部分商品失败,任务会记录失败原因并进入可重试状态;不要仅根据按钮返回就判断所有商品都已成功,应该查看本次执行结果。
## 与交易自动化的边界
“账号自动评价/每日擦亮”处理账号级任务;“自动化规则”处理订单和聊天触发的业务规则:
- 付款后自动发货;
- 评价后发送赠品;
- 超时未评价求评价;
- 关键词回复、默认回复和 AI 回复。
闲鱼官方系统消息只用于平台事件识别,不应被配置为普通买家关键词触发自动回复。
+2
View File
@@ -10,6 +10,8 @@
系统通知卡片只进入自动化判断;买家普通消息走关键词、默认回复和 AI 规则。
账号级自动评价和每日擦亮不属于上表的订单规则,配置入口在“账号管理 → 自动评价与每日擦亮”,执行方式见[在线聊天与账号自动任务](在线聊天与账号自动任务)。
## 配置付款自动发货
前提:账号在线、商品已同步、卡密组已建立且有库存。
+8 -8
View File
@@ -147,8 +147,8 @@ const App: React.FC = () => {
if (checkingAuth) {
return (
<div className="min-h-screen flex items-center justify-center bg-[#f5f5f7]">
<Loader2 className="w-8 h-8 text-[#0094f7] animate-spin" />
<div className="min-h-screen flex items-center justify-center bg-surface">
<Loader2 className="w-8 h-8 text-brand animate-spin" />
</div>
);
}
@@ -156,11 +156,11 @@ const App: React.FC = () => {
// Init Screen (system not initialized)
if (needsInit) {
return (
<div className="min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans">
<div className="min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans">
<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-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="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-xl border border-white relative z-10 animate-fade-in">
<div className="text-center mb-8">
<div className="mx-auto mb-6 flex justify-center">
<YdisksBrandIcon sizeClass="w-24 h-24" />
@@ -198,12 +198,12 @@ const App: React.FC = () => {
// Login Screen Component
if (!isLoggedIn) {
return (
<div className="min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans">
<div className="min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans">
{/* Animated Background Blobs */}
<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-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">
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-lg border border-white relative z-10 animate-fade-in">
{/* Header with Logo */}
<div className="text-center mb-10">
@@ -288,7 +288,7 @@ const App: React.FC = () => {
};
return (
<div className="flex min-h-screen bg-[#F4F5F7] text-[#111]">
<div className="flex min-h-screen bg-canvas text-ink">
<Sidebar
activeTab={activeTab}
isAdmin={isAdmin}
@@ -302,7 +302,7 @@ const App: React.FC = () => {
onLogout={handleLogout}
/>
<main className={`h-screen flex-1 overflow-y-auto scroll-smooth transition-[margin] duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-64'} ${activeTab === 'chat' ? 'p-4 md:p-6' : 'p-8 md:p-12'}`}>
<main className={`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-64'} ${activeTab === 'chat' ? 'p-4 md:p-6' : 'p-8 md:p-12'}`}>
{/* Subtle background decoration */}
<div className="fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"></div>
+3 -1
View File
@@ -45,7 +45,9 @@ Dashboard 的营收趋势柱状图使用统一的品牌蓝 `#0094f7` 表示同
## 路由
应用使用 `window.history.pushState` 做 tab 导航,路径形如 `/app/dashboard`、`/app/rules`、`/app/settings`。
应用使用 `window.history.pushState` 做 tab 导航,路径包括 `/app/dashboard`、`/app/accounts`、
`/app/chat`、`/app/cards`、`/app/items`、`/app/orders`、`/app/rules`、
`/app/notifications` 和管理员可见的 `/app/settings`。
未登录时显示登录表单(客户端状态,非独立路由)。后端 SPA catch-all 对非 API 的 GET 请求返回 `index.html`,支持深链刷新。
## 测试
+15
View File
@@ -37,6 +37,21 @@ describe('online chat UI contract', () => {
expect(chat).toContain('sendChatImage');
});
test('renders official notices as neutral system messages', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain("message.message_type === 'system'");
expect(chat).toContain('justify-center py-1');
});
test('keeps the active chat at the bottom when new messages arrive', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('shouldScrollToBottomRef');
expect(chat).toContain('skipNextMessageScrollRef');
expect(chat).toContain('onScroll={handleMessageScroll}');
expect(chat).toContain('container.scrollHeight - container.scrollTop - container.clientHeight');
expect(chat).toContain('[activeAccountID, activeChatID, messages, messagesLoading]');
});
test('sidebar exposes collapse control and chat primary navigation', () => {
const sidebar = source('components/Sidebar.tsx');
expect(sidebar).toContain("id: 'chat'");
+36
View File
@@ -0,0 +1,36 @@
import { readdirSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
const componentsDir = resolve(__dirname, 'components');
const pageSources = [
resolve(__dirname, 'App.tsx'),
...readdirSync(componentsDir)
.filter((fileName) => fileName.endsWith('.tsx') && !fileName.endsWith('.test.tsx'))
.map((fileName) => resolve(componentsDir, fileName)),
];
// rgb(var(--color-*)), CSS classes and the central index.css are references.
// Literal colors in page code would bypass the design-token system.
const hardCodedColorPattern = /#[0-9a-f]{3,8}\b|rgba?\((?!var\(--color-)/gi;
describe('global color token contract', () => {
test('page components do not contain hard-coded color values', () => {
const violations = pageSources.flatMap((filePath) => {
const source = readFileSync(filePath, 'utf8');
return [...source.matchAll(hardCodedColorPattern)].map((match) => `${filePath}:${match[0]}`);
});
expect(violations).toEqual([]);
});
test('the primary brand and highlight colors are defined in the central stylesheet', () => {
const globalStyles = readFileSync(resolve(__dirname, 'index.css'), 'utf8');
expect(globalStyles).toContain('--color-brand: 0 148 247;');
expect(globalStyles).toContain('--color-brand-highlight: 0 113 227;');
expect(globalStyles).toContain('--color-success-500:');
expect(globalStyles).toContain('--color-warning-500:');
expect(globalStyles).toContain('--color-danger-500:');
});
});
+12 -12
View File
@@ -678,7 +678,7 @@ const AccountList: React.FC = () => {
}
};
if (loading) return <div className="p-20 flex justify-center"><Loader2 className="w-8 h-8 text-[#0094f7] animate-spin"/></div>;
if (loading) return <div className="p-20 flex justify-center"><Loader2 className="w-8 h-8 text-brand animate-spin"/></div>;
const filteredAccounts = accounts.filter(account => {
const keyword = accountSearch.trim().toLowerCase();
@@ -728,7 +728,7 @@ 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 rounded-xl p-6 group transition-all duration-300 hover:border-[#0094f7]">
<div key={account.id} className="ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand">
<div className="flex min-w-0 items-start gap-5 sm:gap-8">
<div className="relative">
{account.avatar_url ? (
@@ -898,7 +898,7 @@ const AccountList: React.FC = () => {
{deleteDialogAccount && createPortal(
<div className="modal-overlay-centered" role="presentation">
<div
className="h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-[0_24px_64px_rgba(15,23,42,0.22)]"
className="h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal"
role="dialog"
aria-modal="true"
aria-labelledby="delete-account-title"
@@ -947,7 +947,7 @@ const AccountList: React.FC = () => {
role="progressbar"
aria-label="正在删除账号"
>
<Loader2 className="h-5 w-5 flex-shrink-0 animate-spin text-[#0094f7]" />
<Loader2 className="h-5 w-5 flex-shrink-0 animate-spin text-brand" />
<div>
<div className="text-sm font-extrabold text-blue-950">正在删除账号</div>
<div className="mt-0.5 text-xs text-blue-700">正在清理关联数据,请保持页面打开…</div>
@@ -1015,8 +1015,8 @@ const AccountList: React.FC = () => {
: '请打开闲鱼APP扫描下方二维码'}
</p>
<div className={`w-full bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${qrStatus === 'verification' ? 'max-w-72 min-h-64 h-auto p-2' : 'max-w-64 aspect-square'}`}>
{qrStatus === 'loading' && <Loader2 className="w-10 h-10 text-[#0094f7] animate-spin" />}
<div className={`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${qrStatus === 'verification' ? 'max-w-72 min-h-64 h-auto p-2' : 'max-w-64 aspect-square'}`}>
{qrStatus === 'loading' && <Loader2 className="w-10 h-10 text-brand animate-spin" />}
{qrStatus === 'waiting' && <SquareQRCode src={qrCodeUrl} alt="闲鱼登录二维码" className="p-2" />}
{qrStatus === 'success' && (
<div className="absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in">
@@ -1111,7 +1111,7 @@ const AccountList: React.FC = () => {
type="button"
onClick={() => setEditForm({ ...editForm, auto_confirm: !editForm.auto_confirm })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
editForm.auto_confirm ? 'bg-[#0094f7]' : 'bg-gray-300'
editForm.auto_confirm ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
@@ -1168,7 +1168,7 @@ const AccountList: React.FC = () => {
aria-label="保存登录信息"
disabled={longLogin.loading || longLogin.saving || !longLogin.canOpen}
onClick={() => void handleLongLoginToggle()}
className={`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${longLogin.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'} disabled:cursor-not-allowed disabled:opacity-50`}
className={`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${longLogin.enabled ? 'bg-brand' : 'bg-gray-300'} disabled:cursor-not-allowed disabled:opacity-50`}
>
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${longLogin.enabled ? 'translate-x-6' : 'translate-x-0'}`} />
</button>
@@ -1206,7 +1206,7 @@ const AccountList: React.FC = () => {
type="checkbox"
checked={editForm.clear_password}
onChange={(e) => setEditForm({ ...editForm, clear_password: e.target.checked, login_password: e.target.checked ? '' : editForm.login_password })}
className="w-4 h-4 accent-[#0094f7]"
className="w-4 h-4 accent-brand"
/>
<span className="text-sm font-bold text-gray-700">清空已保存密码</span>
</label>
@@ -1220,7 +1220,7 @@ const AccountList: React.FC = () => {
type="button"
onClick={() => setEditForm({ ...editForm, show_browser: !editForm.show_browser })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
editForm.show_browser ? 'bg-[#0094f7]' : 'bg-gray-300'
editForm.show_browser ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
@@ -1302,7 +1302,7 @@ const AccountList: React.FC = () => {
}}
disabled={!bindingsLoaded}
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 ? 'bg-brand border-brand' : 'bg-white border-gray-300'
}`}
>
{checked && <Check className="w-3.5 h-3.5 text-white" />}
@@ -1377,7 +1377,7 @@ const AccountList: React.FC = () => {
type="button"
onClick={() => setAiSettings({ ...aiSettings, ai_enabled: !aiSettings.ai_enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
aiSettings.ai_enabled ? 'bg-[#0094f7]' : 'bg-gray-300'
aiSettings.ai_enabled ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
+9 -9
View File
@@ -313,7 +313,7 @@ const CardList: React.FC = () => {
</div>
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
<div className="flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex flex-1 flex-col gap-3 sm:flex-row">
<div className="relative sm:w-48">
<SlidersHorizontal className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
@@ -375,7 +375,7 @@ const CardList: React.FC = () => {
}
return (
<tr key={card.id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
<tr key={card.id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-5 py-5 align-middle">
<div className="flex items-center gap-2.5">
<div className="shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white">
@@ -667,7 +667,7 @@ const CardList: React.FC = () => {
type="button"
onClick={() => setEditForm({ ...editForm, enabled: !editForm.enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
editForm.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'
editForm.enabled ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
@@ -739,7 +739,7 @@ const CardList: React.FC = () => {
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'data', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'data' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'data' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
>
<CreditCard className="w-5 h-5 mx-auto mb-1" />
批量库存
@@ -747,7 +747,7 @@ const CardList: React.FC = () => {
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'text', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'text' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600'}`}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'text' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600'}`}
>
<FileText className="w-5 h-5 mx-auto mb-1" />
文本
@@ -755,7 +755,7 @@ const CardList: React.FC = () => {
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'image', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'image' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600'}`}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'image' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600'}`}
>
<ImageIcon className="w-5 h-5 mx-auto mb-1" />
图片
@@ -792,7 +792,7 @@ const CardList: React.FC = () => {
/>
)}
{addForm.type === 'data' && (
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-[#0094f7]">{addForm.content.split('\n').filter(line => line.trim()).length}</span> 条</p>
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-brand">{addForm.content.split('\n').filter(line => line.trim()).length}</span> 条</p>
)}
</div>
@@ -879,14 +879,14 @@ const CardList: React.FC = () => {
<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'}`}
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-brand 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'}`}
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-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
>
<Upload className="w-4 h-4" />
往单个组充卡密
+43 -9
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import {
AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw,
Search, Send, Smile, UserRound, Wifi, WifiOff,
@@ -53,6 +53,9 @@ const Chat: React.FC = () => {
const activeAccountRef = useRef('');
const activeChatRef = useRef('');
const scrollRef = useRef<HTMLDivElement | null>(null);
const scrollContextRef = useRef({ accountID: '', chatID: '' });
const shouldScrollToBottomRef = useRef(true);
const skipNextMessageScrollRef = useRef(false);
const imageInputRef = useRef<HTMLInputElement | null>(null);
const refreshedAccountsRef = useRef(new Set<string>());
@@ -177,6 +180,7 @@ const Chat: React.FC = () => {
if (!activeAccountID || !activeChatID || olderLoading || !hasOlder) return;
const container = scrollRef.current;
const previousHeight = container?.scrollHeight || 0;
skipNextMessageScrollRef.current = true;
setOlderLoading(true);
setError('');
try {
@@ -192,6 +196,7 @@ const Chat: React.FC = () => {
if (container) container.scrollTop += container.scrollHeight - previousHeight;
});
} catch (loadError) {
skipNextMessageScrollRef.current = false;
setError(loadError instanceof Error ? loadError.message : '加载历史消息失败');
} finally {
setOlderLoading(false);
@@ -261,10 +266,28 @@ const Chat: React.FC = () => {
};
}, []);
useEffect(() => {
const handleMessageScroll = () => {
const container = scrollRef.current;
if (container) container.scrollTop = container.scrollHeight;
}, [activeAccountID, activeChatID, messagesLoading]);
if (!container) return;
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
shouldScrollToBottomRef.current = distanceFromBottom <= 48;
};
useLayoutEffect(() => {
const contextChanged = scrollContextRef.current.accountID !== activeAccountID
|| scrollContextRef.current.chatID !== activeChatID;
scrollContextRef.current = { accountID: activeAccountID, chatID: activeChatID };
if (contextChanged) shouldScrollToBottomRef.current = true;
const container = scrollRef.current;
if (!container) return;
if (skipNextMessageScrollRef.current) {
skipNextMessageScrollRef.current = false;
return;
}
if (messagesLoading || shouldScrollToBottomRef.current) container.scrollTop = container.scrollHeight;
}, [activeAccountID, activeChatID, messages, messagesLoading]);
const activeAccount = accounts.find(account => account.id === activeAccountID);
const activeSessions = sessionsByAccount[activeAccountID] || [];
@@ -343,7 +366,7 @@ const Chat: React.FC = () => {
if (loading) return <div className="flex h-[calc(100vh-4rem)] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-sky-500" /></div>;
return (
<section className="flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-[0_16px_45px_rgba(15,23,42,0.06)]">
<section className="flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat">
<header className="border-b border-slate-200 bg-slate-50/70 px-5 pt-4">
<div className="mb-3 flex items-center justify-between gap-4">
<div>
@@ -400,7 +423,7 @@ const Chat: React.FC = () => {
<div className="min-h-0 flex-1 overflow-y-auto">
{filteredSessions.map(session => (
<button key={session.chat_id} type="button" onClick={() => setActiveChatID(session.chat_id)}
className={`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${session.chat_id === activeChatID ? 'bg-white shadow-[inset_3px_0_0_#0ea5e9]' : 'hover:bg-white/80'}`}>
className={`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${session.chat_id === activeChatID ? 'bg-white shadow-chat-active' : 'hover:bg-white/80'}`}>
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500">
{session.buyer_avatar_url ? <img src={session.buyer_avatar_url} alt="" className="h-full w-full object-cover" /> : <UserRound className="h-5 w-5" />}
</div>
@@ -427,7 +450,7 @@ const Chat: React.FC = () => {
</div>
</aside>
<main className="flex min-h-0 min-w-0 flex-col overflow-hidden bg-[#f7f8fa]">
<main className="flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle">
{selectedSession ? (
<>
<div className="flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5">
@@ -439,7 +462,7 @@ const Chat: React.FC = () => {
{activeAccount?.runtime_state === 'online' ? '账号在线' : '账号离线'}
</span>
</div>
<div ref={scrollRef} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
<div ref={scrollRef} onScroll={handleMessageScroll} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
{messagesLoading ? <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-sky-500" /></div> : <>
{hasOlder && <div className="flex justify-center pb-1">
<button type="button" onClick={() => void loadOlderMessages()} disabled={olderLoading}
@@ -449,6 +472,17 @@ const Chat: React.FC = () => {
</div>}
{messages.map(message => {
const outgoing = message.direction === 'outgoing';
const system = message.message_type === 'system';
if (system) {
return (
<div key={message.message_key} className="flex justify-center py-1">
<div className="max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500">
{renderXianyuText(message.content)}
<div className="mt-1 text-[10px] text-slate-400">{messageTime(message.sent_at)}</div>
</div>
</div>
);
}
return (
<div key={message.message_key} className={`flex items-end gap-2.5 ${outgoing ? 'justify-end' : 'justify-start'}`}>
{!outgoing && <div className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white">
@@ -479,7 +513,7 @@ const Chat: React.FC = () => {
</>}
</div>
{error && <div className="border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700">{error}</div>}
<div className="relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-[0_-8px_24px_rgba(15,23,42,0.04)]">
<div className="relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input">
<div className="mb-2 flex items-center gap-1">
<div className="relative">
<button type="button" onClick={() => setEmojiOpen(value => !value)} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="闲鱼表情"><Smile className="h-5 w-5" /></button>
+2 -3
View File
@@ -33,9 +33,8 @@ describe('Dashboard presentation safeguards', () => {
expect(globalStyles).toContain('.dashboard-pie-chart .recharts-sector:focus');
expect(dashboardSource).toContain('dashboard-revenue-chart h-[350px] w-full');
expect(dashboardSource).toContain('activeBar={false}');
expect(dashboardSource).not.toContain('stroke="#000000"');
expect(dashboardSource).not.toContain("['#0094f7', '#FCD34D', '#0071e3']");
expect(dashboardSource).toContain('fill="#0094f7"');
expect(dashboardSource).not.toMatch(/#[0-9A-Fa-f]{3,8}/);
expect(dashboardSource).toContain("fill={cssColor('brand')}");
expect(globalStyles).toContain('.dashboard-revenue-chart .recharts-rectangle:focus');
expect(globalStyles).toContain('.dashboard-revenue-chart .recharts-curve:focus');
expect(globalStyles).toContain('.dashboard-revenue-chart [class*="recharts-zIndex-layer_"]:focus');
+51 -39
View File
@@ -6,11 +6,17 @@ import { formatLocalDateTime } from '../dateTime';
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend } from 'recharts';
const cssColor = (token: string, alpha?: number) => (
alpha === undefined
? `rgb(var(--color-${token}))`
: `rgb(var(--color-${token}) / ${alpha})`
);
// 状态徽章组件
export const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
const styles = {
processing: 'bg-blue-100 text-blue-800',
pending_ship: 'bg-[#0094f7] text-white',
pending_ship: 'bg-brand text-white',
shipped: 'bg-blue-100 text-blue-700',
completed: 'bg-green-100 text-green-700',
cancelled: 'bg-gray-100 text-gray-500',
@@ -42,7 +48,7 @@ const StatCard: React.FC<{ title: string; value: string | number; icon: React.El
<div className={`p-4 rounded-2xl ${colorClass} bg-opacity-10 backdrop-blur-sm`}>
<Icon className={`w-6 h-6 ${colorClass.replace('bg-', 'text-')}`} />
</div>
{trend && <span className="text-xs font-bold text-white bg-[#0094f7] px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm">
{trend && <span className="text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm">
<TrendingUp className="w-3 h-3" /> {trend}
</span>}
</div>
@@ -75,7 +81,13 @@ const Dashboard: React.FC = () => {
const rangeRequestSequence = useRef(0);
// 颜色配置
const COLORS = ['#0094f7', '#3B82F6', '#10B981', '#F59E0B', '#8B5CF6'];
const COLORS = [
cssColor('brand'),
cssColor('brand-highlight'),
cssColor('success-500'),
cssColor('warning-500'),
cssColor('accent-500'),
];
const formatCurrency = (value: number) => `¥${Number(value || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`;
const loadRange = async (range: TimeRange) => {
let currentRange;
@@ -159,7 +171,7 @@ const Dashboard: React.FC = () => {
</div>
);
}
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-[#0094f7]" /></div>;
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-brand" /></div>;
const chartData = analytics.daily_stats?.map(d => ({
name: d.date.slice(5), // MM-DD
@@ -267,7 +279,7 @@ const Dashboard: React.FC = () => {
onClick={() => setTimeRange(option.key)}
className={`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${
timeRange === option.key
? 'bg-[#0094f7] text-white shadow-md'
? 'bg-brand text-white shadow-md'
: 'bg-white text-gray-600 hover:text-black hover:bg-gray-50'
}`}
>
@@ -280,14 +292,14 @@ const Dashboard: React.FC = () => {
type="date"
value={customStartDate}
onChange={(e) => setCustomStartDate(e.target.value)}
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<span className="self-center text-gray-400">-</span>
<input
type="date"
value={customEndDate}
onChange={(e) => setCustomEndDate(e.target.value)}
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<button
onClick={() => {
@@ -356,26 +368,26 @@ const Dashboard: React.FC = () => {
dataKey="name"
axisLine={false}
tickLine={false}
tick={{fill: '#374151', fontSize: 14, fontWeight: 600}}
tick={{fill: cssColor('neutral-700'), fontSize: 14, fontWeight: 600}}
dy={10}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{fill: '#9CA3AF', fontSize: 13, fontWeight: 500}}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
tickFormatter={(value) => `¥${value}`}
/>
<Tooltip
contentStyle={{
backgroundColor: '#fff',
backgroundColor: cssColor('white'),
borderRadius: '8px',
border: '1px solid #e5e7eb',
boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1)',
border: `1px solid ${cssColor('neutral-200')}`,
boxShadow: 'var(--shadow-xl)',
padding: '12px 16px'
}}
labelStyle={{ color: '#6b7280', fontWeight: 500 }}
itemStyle={{ color: '#0094f7', fontWeight: 600 }}
cursor={{ fill: 'rgba(0, 148, 247, 0.08)' }}
labelStyle={{ color: cssColor('neutral-500'), fontWeight: 500 }}
itemStyle={{ color: cssColor('brand'), fontWeight: 600 }}
cursor={{ fill: cssColor('brand', 0.08) }}
formatter={(value) => {
const num = Number(value);
return [`¥${num.toFixed(2)}`, '营收'];
@@ -383,7 +395,7 @@ const Dashboard: React.FC = () => {
/>
<Bar
dataKey="amount"
fill="#0094f7"
fill={cssColor('brand')}
maxBarSize={72}
radius={[12, 12, 0, 0]}
activeBar={false}
@@ -393,7 +405,7 @@ const Dashboard: React.FC = () => {
{chartData.map((_, index) => (
<Cell
key={`cell-${index}`}
fill="#0094f7"
fill={cssColor('brand')}
stroke="none"
strokeWidth={0}
/>
@@ -407,36 +419,36 @@ const Dashboard: React.FC = () => {
<AreaChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
<defs>
<linearGradient id="colorAmount" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#0094f7" stopOpacity={0.5}/>
<stop offset="95%" stopColor="#0094f7" stopOpacity={0}/>
<stop offset="5%" stopColor={cssColor('brand')} stopOpacity={0.5}/>
<stop offset="95%" stopColor={cssColor('brand')} stopOpacity={0}/>
</linearGradient>
</defs>
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
tick={{fill: '#9CA3AF', fontSize: 13, fontWeight: 500}}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
dy={15}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{fill: '#9CA3AF', fontSize: 13, fontWeight: 500}}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
/>
<CartesianGrid vertical={false} stroke="#F3F4F6" strokeDasharray="3 3" />
<CartesianGrid vertical={false} stroke={cssColor('neutral-100')} strokeDasharray="3 3" />
<Tooltip
contentStyle={{
backgroundColor: '#fff',
backgroundColor: cssColor('white'),
borderRadius: '8px',
border: '1px solid #e5e7eb',
boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1)',
border: `1px solid ${cssColor('neutral-200')}`,
boxShadow: 'var(--shadow-xl)',
padding: '12px 16px'
}}
labelStyle={{ color: '#6b7280', fontWeight: 500 }}
itemStyle={{ color: '#0094f7', fontWeight: 600 }}
cursor={{ stroke: '#0094f7', strokeWidth: 2, strokeDasharray: '4 4' }}
labelStyle={{ color: cssColor('neutral-500'), fontWeight: 500 }}
itemStyle={{ color: cssColor('brand'), fontWeight: 600 }}
cursor={{ stroke: cssColor('brand'), strokeWidth: 2, strokeDasharray: '4 4' }}
/>
<Area type="monotone" dataKey="amount" stroke="#0094f7" strokeWidth={4} fillOpacity={1} fill="url(#colorAmount)" activeDot={{ r: 8, fill: '#fff', stroke: "#0094f7", strokeWidth: 2 }} />
<Area type="monotone" dataKey="amount" stroke={cssColor('brand')} strokeWidth={4} fillOpacity={1} fill="url(#colorAmount)" activeDot={{ r: 8, fill: cssColor('white'), stroke: cssColor('brand'), strokeWidth: 2 }} />
</AreaChart>
</ResponsiveContainer>
)}
@@ -466,7 +478,7 @@ const Dashboard: React.FC = () => {
</div>
<div className="h-3 rounded-full bg-gray-100 overflow-hidden">
<div
className="h-full rounded-full bg-[#0094f7]"
className="h-full rounded-full bg-brand"
style={{ width: `${Math.max(8, (item.sales / maxProductSales) * 100)}%` }}
/>
</div>
@@ -516,17 +528,17 @@ const Dashboard: React.FC = () => {
formatter={(value) => `${Number(value || 0)} 单`}
wrapperStyle={{ zIndex: 30, outline: 'none' }}
contentStyle={{
backgroundColor: '#fff',
border: '1px solid #e5e7eb',
backgroundColor: cssColor('white'),
border: `1px solid ${cssColor('neutral-200')}`,
borderRadius: '10px',
boxShadow: '0 8px 20px rgba(15, 23, 42, 0.08)'
boxShadow: 'var(--shadow-md)'
}}
/>
<Legend
verticalAlign="bottom"
height={36}
iconType="circle"
formatter={(value) => <span style={{ color: '#6B7280', fontWeight: 500 }}>{value}</span>}
formatter={(value) => <span style={{ color: cssColor('neutral-500'), fontWeight: 500 }}>{value}</span>}
/>
</PieChart>
</ResponsiveContainer>
@@ -544,7 +556,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-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]">
<div className="p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted">
<div>
<h3 className="font-bold text-lg text-gray-900">参与统计的订单</h3>
{validOrdersTruncated && (
@@ -603,7 +615,7 @@ const Dashboard: React.FC = () => {
</thead>
<tbody className="divide-y divide-gray-50">
{filteredValidOrders.map((order) => (
<tr key={order.order_id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
<tr key={order.order_id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<div className="w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0">
@@ -687,10 +699,10 @@ const Dashboard: React.FC = () => {
<Tooltip
wrapperStyle={{ zIndex: 30, outline: 'none' }}
contentStyle={{
backgroundColor: '#fff',
border: '1px solid #e5e7eb',
backgroundColor: cssColor('white'),
border: `1px solid ${cssColor('neutral-200')}`,
borderRadius: '6px',
boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
boxShadow: 'var(--shadow-md)'
}}
formatter={(value) => `¥${Number(value || 0).toLocaleString()}`}
/>
+5 -5
View File
@@ -638,14 +638,14 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</button>
<button
onClick={openPublishModal}
className="px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100"
className="px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100"
>
<PackagePlus className="w-4 h-4" />
发布商品
</button>
<button
onClick={() => void openBatchModal()}
className="px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100"
className="px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100"
>
<UploadCloud className="w-4 h-4" />
{recentBatch && ['running', 'canceling'].includes(recentBatch.status) ? '继续批量任务' : '批量铺货'}
@@ -670,7 +670,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<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-1.5 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-brand hover:text-white transition-colors"
title="编辑"
>
<Edit className="w-3.5 h-3.5" />
@@ -710,7 +710,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<div className="space-y-2 mt-auto">
<button
onClick={() => onConfigureDelivery(item)}
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'}`}
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-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100'}`}
>
<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" />
@@ -892,7 +892,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</div>
</div>
<div className="modal-footer">
<button disabled={publishing} onClick={handlePublishItem} className="w-full bg-emerald-600 hover:bg-emerald-700 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
<button disabled={publishing} onClick={handlePublishItem} className="w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
<PackagePlus className="w-4 h-4" />
{publishing ? '正在发布...' : '发布到闲鱼'}
</button>
+12 -13
View File
@@ -394,7 +394,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
{/* 说明 */}
<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" />
<Bell className="w-5 h-5 text-brand 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">
@@ -409,7 +409,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
{/* 渠道列表 */}
{loading ? (
<div className="flex justify-center py-20">
<Loader2 className="w-8 h-8 text-[#0094f7] animate-spin" />
<Loader2 className="w-8 h-8 text-brand animate-spin" />
</div>
) : channels.length === 0 ? (
<div className="ios-card rounded-xl p-12 bg-white text-center">
@@ -454,7 +454,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
<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"
className="px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand 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" />}
测试
@@ -639,10 +639,10 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
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'}`}
className={`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${selected ? 'border-brand 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>
<TIcon className={`w-5 h-5 ${selected ? 'text-brand' : 'text-gray-500'}`} />
<span className={`text-xs font-bold ${selected ? 'text-brand' : 'text-gray-600'}`}>{m.label}</span>
</button>
);
})}
@@ -712,7 +712,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
: enableCustomSMTP(form.config, smtp),
});
}}
className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-brand' : 'bg-gray-300'}`}
aria-label="使用独立 SMTP"
>
<span className={`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${form.config.use_custom_smtp === true ? 'translate-x-5' : ''}`} />
@@ -839,13 +839,13 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
: [...form.event_types, event.value];
setForm({ ...form, event_types: next });
}}
className={`text-left rounded-xl border px-3 py-2.5 transition-colors ${checked ? 'border-[#0094f7] bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
className={`text-left rounded-xl border px-3 py-2.5 transition-colors ${checked ? 'border-brand bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
>
<div className="flex items-center gap-2">
<span className={`w-4 h-4 rounded border flex items-center justify-center ${checked ? 'bg-[#0094f7] border-[#0094f7]' : 'border-gray-300'}`}>
<span className={`w-4 h-4 rounded border flex items-center justify-center ${checked ? 'bg-brand border-brand' : 'border-gray-300'}`}>
{checked && <Check className="w-3 h-3 text-white" />}
</span>
<span className={`text-sm font-bold ${checked ? 'text-[#0094f7]' : 'text-gray-800'}`}>{event.label}</span>
<span className={`text-sm font-bold ${checked ? 'text-brand' : 'text-gray-800'}`}>{event.label}</span>
</div>
<p className="text-xs text-gray-500 mt-1 pl-6 leading-5">{event.description}</p>
</button>
@@ -858,7 +858,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
<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'}`}
className={`relative w-11 h-6 rounded-full transition-colors ${form.enabled ? 'bg-brand' : '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>
@@ -889,8 +889,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
{/* 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' }}>
<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 text-white ${toast.type === 'success' ? 'bg-success-500' : 'bg-danger-500'}`}>
{toast.type === 'success' ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
{toast.text}
</div>
+5 -5
View File
@@ -9,7 +9,7 @@ import { formatLocalDateTime } from '../dateTime';
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
const styles = {
processing: 'bg-blue-100 text-blue-800',
pending_ship: 'bg-[#0094f7] text-white',
pending_ship: 'bg-brand text-white',
shipped: 'bg-blue-100 text-blue-700',
completed: 'bg-green-100 text-green-700',
cancelled: 'bg-gray-100 text-gray-500',
@@ -356,7 +356,7 @@ const OrderList: React.FC = () => {
<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="p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted">
<div className="flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full">
{[
{k:'all', v:'全部'},
@@ -392,7 +392,7 @@ const OrderList: React.FC = () => {
</select>
</div>
<div className="relative group">
<Search className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors" />
<Search className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors" />
<input
type="text"
placeholder="搜索订单号/商品/买家..."
@@ -418,7 +418,7 @@ const OrderList: React.FC = () => {
</thead>
<tbody className="divide-y divide-gray-50">
{orders.map((order) => (
<tr key={order.id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
<tr key={order.id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-6 py-5">
<div className="flex items-center gap-5">
<div className="w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0">
@@ -800,7 +800,7 @@ const OrderList: React.FC = () => {
<button
onClick={() => executeShip('full_delivery')}
disabled={shipLoading}
className="w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-[#0094f7] hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
className="w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="flex items-start gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5">
+20 -30
View File
@@ -232,6 +232,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
const [automationPageSize, setAutomationPageSize] = useState(10);
const [automationTotal, setAutomationTotal] = useState(0);
const [automationTotalPages, setAutomationTotalPages] = useState(0);
const [automationTriggerCounts, setAutomationTriggerCounts] = useState<Record<string, number>>({});
const automationRulesRequest = useRef(0);
const replyRulesRequest = useRef(0);
const selectedAccountRef = useRef('');
@@ -283,6 +284,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
setAutomationRules(result.data);
setAutomationTotal(result.total);
setAutomationTotalPages(result.total_pages);
setAutomationTriggerCounts(result.trigger_counts || {});
if (result.page !== automationPage) setAutomationPage(result.page);
const issues = await issuesPromise;
if (requestID !== automationRulesRequest.current) return;
@@ -351,18 +353,6 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
[accounts, selectedAccountId],
);
const rulesByTrigger = useMemo(() => {
const grouped: Record<AutomationTriggerType, ShippingRule[]> = {
order_paid: [],
buyer_reviewed: [],
review_missing_timeout: [],
};
for (const rule of visibleAutomationRules) {
grouped[rule.trigger_type]?.push(rule);
}
return grouped;
}, [visibleAutomationRules]);
const automationPageNumbers = useMemo(() => {
if (automationTotalPages <= 1) return [];
const first = Math.max(1, Math.min(automationPage - 2, automationTotalPages - 4));
@@ -801,7 +791,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
: '编辑默认回复';
return (
<div className="space-y-8 animate-fade-in">
<div className="min-w-0 space-y-8 animate-fade-in">
<div className="flex flex-col xl:flex-row justify-between xl:items-end gap-4">
<div>
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">自动化规则</h2>
@@ -814,7 +804,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
setSelectedAccountId(event.target.value);
setAutomationPage(1);
}}
className="ios-input px-4 py-3 rounded-2xl text-sm min-w-64"
className="ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64"
>
<option value="">全部账号</option>
{accounts.map(account => (
@@ -852,7 +842,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
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-brand text-white shadow-md'
: 'bg-white text-gray-600 hover:text-black hover:bg-gray-50'
}`}
>
@@ -904,8 +894,8 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
)}
{activeTab === 'automation' && (
<div className="grid grid-cols-1 2xl:grid-cols-[360px_1fr] gap-6">
<aside className="space-y-4">
<div className="grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]">
<aside className="min-w-0 space-y-4">
<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>
@@ -937,7 +927,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm">
<div className="mb-4 flex items-center justify-between gap-3">
<h3 className="font-black text-gray-900">本页规则构成</h3>
<h3 className="font-black text-gray-900">筛选结果构成</h3>
<span className="text-xs font-bold text-gray-400">共 {automationTotal} 条</span>
</div>
<div className="space-y-3">
@@ -950,7 +940,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<Icon className="w-4 h-4 text-gray-500" />
<span className="text-sm font-bold text-gray-700">{meta.shortLabel}</span>
</div>
<span className="text-sm font-black text-gray-900">{rulesByTrigger[trigger].length}</span>
<span className="text-sm font-black text-gray-900">{automationTriggerCounts[trigger] || 0}</span>
</div>
);
})}
@@ -958,8 +948,8 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
</div>
</aside>
<section className="space-y-4">
<div className="rounded-xl border border-gray-100 bg-[#FAFAFA] p-4 shadow-sm">
<section className="min-w-0 space-y-4">
<div className="rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm">
<div className="flex flex-col gap-3 xl:flex-row xl:items-center">
<div className="relative min-w-0 flex-1">
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
@@ -1122,7 +1112,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
type="button"
disabled={loading}
onClick={() => setAutomationPage(pageNumber)}
className={`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${pageNumber === automationPage ? 'bg-[#0094f7] text-white' : 'bg-gray-50 text-gray-600 hover:bg-gray-100'} disabled:cursor-not-allowed disabled:opacity-60`}
className={`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${pageNumber === automationPage ? 'bg-brand text-white' : 'bg-gray-50 text-gray-600 hover:bg-gray-100'} disabled:cursor-not-allowed disabled:opacity-60`}
aria-label={`第 ${pageNumber} 页`}
aria-current={pageNumber === automationPage ? 'page' : undefined}
>
@@ -1154,7 +1144,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
</div>
<div className="space-y-3">
{replyRules.map(rule => (
<div key={rule.id} className="flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg transition-all gap-4">
<div key={rule.id} className="flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg transition-all gap-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-2">
<span className="px-3 py-1 bg-black text-white rounded-lg text-xs font-bold">包含匹配</span>
@@ -1197,7 +1187,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
const defaultReply = defaultReplies[account.id];
const enabled = Boolean(defaultReply?.enabled);
return (
<div key={account.id} className={`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${enabled ? 'border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg' : 'border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg'}`}>
<div key={account.id} className={`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${enabled ? 'border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg' : 'border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg'}`}>
<div className="flex items-center gap-4 min-w-0">
<div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${enabled ? 'bg-purple-600 text-white' : 'bg-gray-200 text-gray-400'}`}>
<Bot className="w-5 h-5" />
@@ -1282,7 +1272,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
}`}
>
<div className="flex items-start gap-3">
<Icon className={`w-5 h-5 mt-0.5 ${selected ? 'text-[#0094f7]' : 'text-white'}`} />
<Icon className={`w-5 h-5 mt-0.5 ${selected ? 'text-brand' : 'text-white'}`} />
<div>
<div className="font-black">{meta.label}</div>
<div className={`text-xs mt-1 leading-5 ${selected ? 'text-gray-500' : 'text-gray-400'}`}>{meta.description}</div>
@@ -1306,11 +1296,11 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
</div>
</aside>
<div className="p-6 overflow-y-auto bg-[#F7F8FA]">
<div className="p-6 overflow-y-auto bg-surface-subtle">
<div className="space-y-5">
<section className="bg-white rounded-3xl border border-gray-100 p-5">
<div className="flex items-center gap-2 mb-4">
<CheckCircle2 className="w-5 h-5 text-[#0094f7]" />
<CheckCircle2 className="w-5 h-5 text-brand" />
<h4 className="font-black text-gray-900">生效范围</h4>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
@@ -1379,7 +1369,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<div className="flex items-start justify-between gap-4 mb-4">
<div>
<div className="flex items-center gap-2">
<Layers3 className="w-5 h-5 text-[#0094f7]" />
<Layers3 className="w-5 h-5 text-brand" />
<h4 className="font-black text-gray-900">{currentTrigger === 'buyer_reviewed' ? '赠品库存' : '发货库存'}</h4>
</div>
<p className="text-sm text-gray-500 mt-1">
@@ -1456,7 +1446,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
type="checkbox"
checked={variant.delay_override === true}
onChange={event => updateVariant(index, { delay_override: event.target.checked })}
className="accent-[#0094f7]"
className="accent-brand"
/>
覆盖卡密默认延时
</label>
@@ -1748,7 +1738,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<button
type="button"
onClick={() => setDefaultForm({ ...defaultForm, enabled: !defaultForm.enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${defaultForm.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${defaultForm.enabled ? 'bg-brand' : 'bg-gray-300'}`}
>
<span className={`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${defaultForm.enabled ? 'translate-x-7' : 'translate-x-1'}`} />
</button>
+3 -3
View File
@@ -269,7 +269,7 @@ const Settings: React.FC = () => {
{/* AI Configuration */}
<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-[#0094f7] text-white">
<div className="p-1.5 rounded-lg bg-brand text-white">
<Sparkles className="w-4 h-4" />
</div>
AI 智能回复配置
@@ -346,10 +346,10 @@ const Settings: React.FC = () => {
setSettings({...settings, ai_model: model});
setModelDropdownOpen(false);
}}
className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-[#0094f7] flex items-center justify-between gap-3"
className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3"
>
<span className="truncate">{model}</span>
{model === currentModel && <Check className="w-4 h-4 shrink-0 text-[#0094f7]" />}
{model === currentModel && <Check className="w-4 h-4 shrink-0 text-brand" />}
</button>
))
) : (
+2 -2
View File
@@ -30,7 +30,7 @@ const Sidebar: React.FC<SidebarProps> = ({
];
return (
<aside className={`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-[4px_0_24px_rgba(15,23,42,0.035)] backdrop-blur-xl transition-[width] duration-300 ${collapsed ? 'w-16' : 'w-64'}`}>
<aside className={`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${collapsed ? 'w-16' : 'w-64'}`}>
<div className={`flex h-20 items-center border-b border-slate-100 ${collapsed ? 'justify-center px-2' : 'gap-3 px-5'}`}>
<YdisksBrandIcon sizeClass="h-10 w-10" />
{!collapsed && (
@@ -55,7 +55,7 @@ const Sidebar: React.FC<SidebarProps> = ({
onClick={() => onNavigate(item.id)}
className={`group relative flex h-11 w-full items-center rounded-xl transition-colors ${collapsed ? 'justify-center' : 'gap-3 px-3.5'} ${
active
? 'bg-sky-500 text-white shadow-[0_8px_18px_rgba(14,165,233,0.2)]'
? 'bg-brand text-white shadow-brand-active'
: 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
}`}
>
+2 -2
View File
@@ -27,8 +27,8 @@ export const YdisksBrandIcon: React.FC<YdisksBrandIconProps> = ({
<svg className="absolute inset-0 w-full h-full" viewBox="0 0 120 120" aria-hidden="true">
<defs>
<linearGradient id="login-squircle-gradient" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#0094f7" />
<stop offset="100%" stopColor="#287efe" />
<stop offset="0%" stopColor="rgb(var(--color-brand))" />
<stop offset="100%" stopColor="rgb(var(--color-brand-light))" />
</linearGradient>
</defs>
<path d="M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z" fill="url(#login-squircle-gradient)" />
+210 -59
View File
@@ -3,6 +3,157 @@
@tailwind components;
@tailwind utilities;
/*
* 全局颜色令牌:页面组件不得直接写颜色值。
* 颜色使用 RGB 通道存储,Tailwind 和 CSS 可以安全地复用透明度。
*/
:root {
--color-transparent: transparent;
--color-black: 0 0 0;
--color-white: 255 255 255;
--color-brand: 0 148 247;
--color-brand-highlight: 0 113 227;
--color-brand-light: 40 126 254;
--color-ink: 29 29 31;
--color-muted: 134 134 139;
--color-line: 210 210 215;
--color-canvas: 244 245 247;
--color-surface: 255 255 255;
--color-surface-subtle: 247 248 250;
--color-surface-muted: 250 250 250;
--color-neutral-50: 249 250 251;
--color-neutral-100: 243 244 246;
--color-neutral-200: 229 231 235;
--color-neutral-300: 209 213 219;
--color-neutral-400: 156 163 175;
--color-neutral-500: 107 114 128;
--color-neutral-600: 75 85 99;
--color-neutral-700: 55 65 81;
--color-neutral-800: 31 41 55;
--color-neutral-900: 17 24 39;
--color-neutral-950: 3 7 18;
--color-slate-50: 248 250 252;
--color-slate-100: 241 245 249;
--color-slate-200: 226 232 240;
--color-slate-300: 203 213 225;
--color-slate-400: 148 163 184;
--color-slate-500: 100 116 139;
--color-slate-600: 71 85 105;
--color-slate-700: 51 65 85;
--color-slate-800: 30 41 59;
--color-slate-900: 15 23 42;
--color-slate-950: 2 6 23;
/* 主色阶:蓝色只从品牌色体系中取值,避免 blue/sky 各自漂移。 */
--color-brand-50: 239 248 255;
--color-brand-100: 223 241 255;
--color-brand-200: 191 229 255;
--color-brand-300: 143 210 255;
--color-brand-400: 83 184 251;
--color-brand-500: 0 148 247;
--color-brand-600: 0 148 247;
--color-brand-700: 0 113 227;
--color-brand-800: 0 91 181;
--color-brand-900: 0 75 147;
--color-brand-950: 0 53 107;
--color-success-50: 236 253 245;
--color-success-100: 209 250 229;
--color-success-200: 167 243 208;
--color-success-300: 110 231 183;
--color-success-400: 52 211 153;
--color-success-500: 16 185 129;
--color-success-600: 5 150 105;
--color-success-700: 4 120 87;
--color-success-800: 6 95 70;
--color-success-900: 6 78 59;
--color-success-950: 2 44 34;
--color-warning-50: 255 251 235;
--color-warning-100: 254 243 199;
--color-warning-200: 253 230 138;
--color-warning-300: 252 211 77;
--color-warning-400: 251 191 36;
--color-warning-500: 245 158 11;
--color-warning-600: 217 119 6;
--color-warning-700: 180 83 9;
--color-warning-800: 146 64 14;
--color-warning-900: 120 53 15;
--color-warning-950: 69 26 3;
--color-danger-50: 254 242 242;
--color-danger-100: 254 226 226;
--color-danger-200: 254 202 202;
--color-danger-300: 252 165 165;
--color-danger-400: 248 113 113;
--color-danger-500: 239 68 68;
--color-danger-600: 220 38 38;
--color-danger-700: 185 28 28;
--color-danger-800: 153 27 27;
--color-danger-900: 127 29 29;
--color-danger-950: 69 10 10;
--color-info-50: 239 246 255;
--color-info-100: 219 234 254;
--color-info-200: 191 219 254;
--color-info-300: 147 197 253;
--color-info-400: 96 165 250;
--color-info-500: 59 130 246;
--color-info-600: 37 99 235;
--color-info-700: 29 78 216;
--color-info-800: 30 64 175;
--color-info-900: 30 58 138;
--color-info-950: 23 37 84;
/* 非状态性的辅助色只保留一个紫色阶,避免页面出现过多彩色分支。 */
--color-accent-50: 250 245 255;
--color-accent-100: 243 232 255;
--color-accent-200: 233 213 255;
--color-accent-300: 216 180 254;
--color-accent-400: 192 132 252;
--color-accent-500: 168 85 247;
--color-accent-600: 147 51 234;
--color-accent-700: 126 34 206;
--color-accent-800: 107 33 168;
--color-accent-900: 88 28 135;
--color-accent-950: 59 7 100;
--shadow-none: 0 0 0 var(--color-transparent);
--shadow-default: 0 1px 3px 0 rgb(var(--color-black) / 0.1), 0 1px 2px -1px rgb(var(--color-black) / 0.1);
--shadow-sm: 0 1px 2px 0 rgb(var(--color-black) / 0.05);
--shadow-md: 0 4px 6px -1px rgb(var(--color-black) / 0.1), 0 2px 4px -2px rgb(var(--color-black) / 0.1);
--shadow-lg: 0 10px 15px -3px rgb(var(--color-black) / 0.1), 0 4px 6px -4px rgb(var(--color-black) / 0.1);
--shadow-xl: 0 20px 25px -5px rgb(var(--color-black) / 0.1), 0 8px 10px -6px rgb(var(--color-black) / 0.1);
--shadow-2xl: 0 25px 50px -12px rgb(var(--color-black) / 0.25);
--shadow-inner: inset 0 2px 4px 0 rgb(var(--color-black) / 0.05);
--shadow-card: 0 8px 24px rgb(var(--color-black) / 0.04);
--shadow-panel: 0 20px 60px -15px rgb(var(--color-black) / 0.05);
--shadow-modal: 0 25px 50px -12px rgb(var(--color-black) / 0.25);
--shadow-sidebar: 4px 0 24px rgb(var(--color-slate-900) / 0.035);
--shadow-chat: 0 16px 45px rgb(var(--color-slate-900) / 0.06);
--shadow-chat-input: 0 -8px 24px rgb(var(--color-slate-900) / 0.04);
--shadow-chat-active: inset 3px 0 0 rgb(var(--color-brand));
--shadow-brand-soft: 0 2px 8px rgb(var(--color-brand) / 0.2);
--shadow-brand-active: 0 8px 18px rgb(var(--color-brand) / 0.2);
--shadow-brand-strong: 0 8px 20px rgb(var(--color-brand) / 0.3);
}
/* 覆盖 Tailwind 默认的蓝色焦点环和黑色占位阴影,避免预设色偷偷进入页面。 */
*,
::before,
::after {
--tw-ring-offset-color: rgb(var(--color-white));
--tw-ring-color: rgb(var(--color-brand-400) / 0.5);
--tw-ring-offset-shadow: 0 0 0 var(--color-transparent);
--tw-ring-shadow: 0 0 0 var(--color-transparent);
--tw-shadow: 0 0 0 var(--color-transparent);
--tw-shadow-colored: 0 0 0 var(--color-transparent);
}
/* Ydisks 超椭圆 logo 容器:用 squircle mask 实现真超椭圆(比圆角矩形更鼓)。
mask 让容器背景色(蓝)也裁成超椭圆形状。
shadow 改用 filter:drop-shadow,跟随 mask 后的实际形状(box-shadow 会被 mask 裁掉)。 */
@@ -34,23 +185,23 @@ html, body, #root {
body {
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color: #F4F5F7;
color: #ffffff;
background-color: rgb(var(--color-canvas));
color: rgb(var(--color-ink));
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* 闲鱼风格卡片 */
.ios-card {
background: #FFFFFF;
background: rgb(var(--color-surface));
border-radius: 8px;
border: 1px solid rgba(0, 0, 0, 0.02);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
border: 1px solid rgb(var(--color-black) / 0.02);
box-shadow: var(--shadow-card);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.ios-card:hover {
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.06);
box-shadow: 0 12px 32px rgb(var(--color-black) / 0.06);
}
/* 仪表盘饼图是展示型图表,避免 Recharts 的 SVG 焦点框和扇区焦点框形成无意义长条。 */
@@ -78,29 +229,29 @@ body {
/* 闲鱼风格输入框 */
.ios-input {
background: #F7F8FA;
border: 1px solid transparent;
background: rgb(var(--color-surface-subtle));
border: 1px solid var(--color-transparent);
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
color: #111;
color: rgb(var(--color-ink));
font-weight: 500;
}
.ios-input:focus {
background: #FFFFFF;
border-color: #0094f7;
box-shadow: 0 0 0 4px rgba(0, 148, 247, 0.3);
background: rgb(var(--color-surface));
border-color: rgb(var(--color-brand));
box-shadow: 0 0 0 4px rgb(var(--color-brand) / 0.3);
outline: none;
}
.ios-input::placeholder {
color: #9CA3AF;
color: rgb(var(--color-neutral-400));
font-weight: 400;
}
/* 主按钮 */
.ios-btn-primary {
background: #0094f7;
color: #ffffff;
background: rgb(var(--color-brand));
color: rgb(var(--color-white));
font-weight: 700;
border: none;
transition: all 0.2s cubic-bezier(0.25, 0.8, 0.25, 1);
@@ -108,19 +259,19 @@ body {
}
.ios-btn-primary:hover:not(:disabled) {
background: #0071e3;
background: rgb(var(--color-brand-highlight));
transform: translateY(-1px);
box-shadow: 0 8px 20px rgba(0, 148, 247, 0.3);
box-shadow: var(--shadow-brand-strong);
}
.ios-btn-primary:active:not(:disabled) {
transform: translateY(1px);
box-shadow: 0 2px 8px rgba(0, 148, 247, 0.2);
box-shadow: var(--shadow-brand-soft);
}
.ios-btn-primary:disabled {
background: #F0F0F0;
color: #AAAAAA;
background: rgb(var(--color-neutral-100));
color: rgb(var(--color-neutral-400));
box-shadow: none;
transform: none;
cursor: not-allowed;
@@ -128,32 +279,32 @@ body {
/* 次要按钮 */
.ios-btn-secondary {
background: #F7F8FA;
color: #ffffff;
background: rgb(var(--color-surface-subtle));
color: rgb(var(--color-ink));
font-weight: 600;
border: 1px solid transparent;
border: 1px solid var(--color-transparent);
transition: all 0.2s ease;
cursor: pointer;
}
.ios-btn-secondary:hover {
background: #E5E7EB;
border-color: #D1D5DB;
background: rgb(var(--color-neutral-200));
border-color: rgb(var(--color-neutral-300));
}
/* 危险按钮 */
.ios-btn-danger {
background: #FEE2E2;
color: #DC2626;
background: rgb(var(--color-danger-100));
color: rgb(var(--color-danger-600));
font-weight: 600;
border: 1px solid transparent;
border: 1px solid var(--color-transparent);
transition: all 0.2s ease;
cursor: pointer;
}
.ios-btn-danger:hover {
background: #FECACA;
border-color: #FCA5A5;
background: rgb(var(--color-danger-200));
border-color: rgb(var(--color-danger-300));
}
/* 自定义滚动条 */
@@ -163,16 +314,16 @@ body {
}
::-webkit-scrollbar-track {
background: transparent;
background: var(--color-transparent);
}
::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.1);
background: rgb(var(--color-black) / 0.1);
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 0, 0, 0.2);
background: rgb(var(--color-black) / 0.2);
}
/* 动画 */
@@ -234,21 +385,21 @@ body {
/* 文本选择 */
::selection {
background: #0094f7;
color: #fff;
background: rgb(var(--color-brand));
color: rgb(var(--color-white));
}
/* 工具类 */
.text-brand {
color: #0094f7;
color: rgb(var(--color-brand));
}
.bg-brand {
background-color: #0094f7;
background-color: rgb(var(--color-brand));
}
.border-brand {
border-color: #0094f7;
border-color: rgb(var(--color-brand));
}
/* 状态徽章 */
@@ -262,31 +413,31 @@ body {
}
.status-badge-success {
background-color: #D1FAE5;
color: #065F46;
background-color: rgb(var(--color-success-100));
color: rgb(var(--color-success-800));
}
.status-badge-warning {
background-color: #FEF3C7;
color: #92400E;
background-color: rgb(var(--color-warning-100));
color: rgb(var(--color-warning-800));
}
.status-badge-error {
background-color: #FEE2E2;
color: #991B1B;
background-color: rgb(var(--color-danger-100));
color: rgb(var(--color-danger-800));
}
.status-badge-info {
background-color: #DBEAFE;
color: #1E40AF;
background-color: rgb(var(--color-info-100));
color: rgb(var(--color-info-800));
}
/* 加载状态 */
.loading-skeleton {
background: linear-gradient(90deg,
#F3F4F6 0%,
#E5E7EB 50%,
#F3F4F6 100%);
rgb(var(--color-neutral-100)) 0%,
rgb(var(--color-neutral-200)) 50%,
rgb(var(--color-neutral-100)) 100%);
background-size: 200% 100%;
animation: loading 1.5s ease-in-out infinite;
}
@@ -308,7 +459,7 @@ body {
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.4);
background-color: rgb(var(--color-black) / 0.4);
backdrop-filter: blur(8px);
padding: 1rem;
overflow-y: auto;
@@ -322,17 +473,17 @@ body {
margin: auto;
display: flex;
flex-direction: column;
background-color: white;
background-color: rgb(var(--color-white));
border-radius: 10px;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
box-shadow: var(--shadow-modal);
overflow: hidden;
}
.modal-header {
flex-shrink: 0;
padding: 2rem 2rem 1.5rem;
border-bottom: 1px solid #F3F4F6;
background-color: white;
border-bottom: 1px solid rgb(var(--color-neutral-100));
background-color: rgb(var(--color-white));
z-index: 10;
}
@@ -346,8 +497,8 @@ body {
.modal-footer {
flex-shrink: 0;
padding: 1.5rem 2rem 2rem;
border-top: 1px solid #F3F4F6;
background-color: white;
border-top: 1px solid rgb(var(--color-neutral-100));
background-color: rgb(var(--color-white));
z-index: 10;
}
@@ -363,7 +514,7 @@ body {
z-index: 9999;
display: flex;
justify-content: center;
background-color: rgba(0, 0, 0, 0.4);
background-color: rgb(var(--color-black) / 0.4);
backdrop-filter: blur(8px);
padding: 1rem;
overflow-y: auto;
@@ -377,9 +528,9 @@ body {
margin: auto 0;
display: flex;
flex-direction: column;
background-color: white;
background-color: rgb(var(--color-white));
border-radius: 10px;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
box-shadow: var(--shadow-modal);
overflow: hidden;
}
+17
View File
@@ -0,0 +1,17 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
const itemList = readFileSync(resolve(__dirname, 'components/ItemList.tsx'), 'utf8');
describe('item list primary action colors', () => {
test('uses the shared primary blue for batch publishing', () => {
expect(itemList).toContain('bg-brand text-white hover:bg-brand-highlight');
expect(itemList).not.toContain('bg-blue-600 text-white hover:bg-blue-700');
});
test('uses the lighter emerald tone for publishing actions', () => {
expect(itemList).toContain('bg-emerald-500 text-white hover:bg-emerald-600');
expect(itemList).not.toContain('bg-emerald-600 text-white hover:bg-emerald-700');
});
});
+7
View File
@@ -26,6 +26,13 @@ describe('frontend navigation routing', () => {
expect([...sidebarIDs].sort()).toEqual([...appRouteIDs].sort());
});
test('active navigation uses the primary action blue', () => {
const sidebar = readFrontendFile('components/Sidebar.tsx');
expect(sidebar).toContain("'bg-brand text-white shadow-brand-active'");
expect(sidebar).not.toContain("'bg-sky-500 text-white'");
});
test('logout button invalidates the backend session before clearing UI state', () => {
const app = readFrontendFile('App.tsx');
+28
View File
@@ -0,0 +1,28 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8');
describe('responsive rules layout', () => {
test('allows the rules page to shrink inside the sidebar layout', () => {
const app = source('App.tsx');
const rules = source('components/Rules.tsx');
expect(app).toContain('h-screen min-w-0 flex-1 overflow-x-hidden');
expect(rules).toContain('min-w-0 space-y-8');
expect(rules).toContain('xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]');
expect(rules).not.toContain('2xl:grid-cols-[360px_1fr]');
});
});
describe('rules summary counts', () => {
test('uses server-side aggregate counts instead of the current page length', () => {
const rules = source('components/Rules.tsx');
const api = source('services/api.ts');
expect(rules).toContain('automationTriggerCounts');
expect(rules).toContain('{automationTriggerCounts[trigger] || 0}');
expect(rules).toContain('筛选结果构成');
expect(rules).not.toContain('rulesByTrigger[trigger].length');
expect(api).toContain('trigger_counts');
});
});
+8 -1
View File
@@ -152,6 +152,7 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
page: 2,
page_size: 20,
total_pages: 2,
trigger_counts: { order_paid: 8, buyer_reviewed: 7, review_missing_timeout: 6 },
}));
vi.stubGlobal('fetch', fetchMock);
@@ -164,7 +165,13 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
pageSize: 20,
});
expect(result).toMatchObject({ total: 21, page: 2, page_size: 20, total_pages: 2 });
expect(result).toMatchObject({
total: 21,
page: 2,
page_size: 20,
total_pages: 2,
trigger_counts: { order_paid: 8, buyer_reviewed: 7, review_missing_timeout: 6 },
});
expect(result.data[0]).toMatchObject({ id: '7', name: '付款规则', enabled: false });
expect(fetchMock).toHaveBeenCalledWith(
'/automation-rules?page=2&page_size=20&cookie_id=acc1&trigger_type=order_paid&enabled=false&search=%E5%95%86%E5%93%81',
+3
View File
@@ -686,6 +686,9 @@ export const getShippingRulesPage = async ({
page: Number(res.page ?? page),
page_size: Number(res.page_size ?? pageSize),
total_pages: Number(res.total_pages ?? (rules.length ? 1 : 0)),
trigger_counts: Object.fromEntries(
Object.entries(res.trigger_counts || {}).map(([key, value]) => [key, Number(value)]),
),
};
}
+62 -10
View File
@@ -1,3 +1,10 @@
const color = (token) => `rgb(var(--color-${token}) / <alpha-value>)`;
const palette = (name) => Object.fromEntries(
[50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]
.map((shade) => [shade, color(`${name}-${shade}`)]),
);
/** @type {import('tailwindcss').Config} */
export default {
content: [
@@ -8,18 +15,40 @@ export default {
theme: {
extend: {
colors: {
// Ydisks 官网配色:Apple 风格蓝色系 + 浅灰背景 + 深色文字。
// 具体色值统一维护在 index.css 的 --color-* 令牌中,组件只使用语义化 Tailwind 类名。
transparent: 'var(--color-transparent)',
current: 'currentColor',
black: color('black'),
white: color('white'),
brand: {
DEFAULT: '#0094f7', // 主品牌蓝(Ydisks logo/按钮色)
dark: '#0071e3', // 深蓝(hover/强调)
light: '#287efe', // 亮蓝(辅助)
DEFAULT: color('brand'),
highlight: color('brand-highlight'),
light: color('brand-light'),
},
// Ydisks 中性色
ink: '#1d1d1f', // 主文字
muted: '#86868b', // 次要文字
line: '#d2d2d7', // 边框/分隔
canvas: '#fbfbfd', // 页面背景
surface: '#f5f5f7', // 卡片背景/区块
ink: color('ink'),
muted: color('muted'),
line: color('line'),
canvas: color('canvas'),
surface: color('surface'),
'surface-subtle': color('surface-subtle'),
'surface-muted': color('surface-muted'),
success: palette('success'),
warning: palette('warning'),
danger: palette('danger'),
info: palette('info'),
// 保留现有 Tailwind 语义类,但统一指向同一套设计令牌。
gray: palette('neutral'),
slate: palette('slate'),
blue: palette('brand'),
sky: palette('brand'),
emerald: palette('success'),
green: palette('success'),
amber: palette('warning'),
orange: palette('warning'),
red: palette('danger'),
yellow: palette('warning'),
purple: palette('accent'),
pink: palette('accent'),
},
// 圆角统一收紧到 5–10px 区间,UI 更紧凑、信息密度更高。
borderRadius: {
@@ -45,6 +74,29 @@ export default {
'sans-serif',
],
},
accentColor: {
brand: color('brand'),
},
boxShadow: {
none: 'var(--shadow-none)',
sm: 'var(--shadow-sm)',
DEFAULT: 'var(--shadow-default)',
md: 'var(--shadow-md)',
lg: 'var(--shadow-lg)',
xl: 'var(--shadow-xl)',
'2xl': 'var(--shadow-2xl)',
inner: 'var(--shadow-inner)',
card: 'var(--shadow-card)',
panel: 'var(--shadow-panel)',
modal: 'var(--shadow-modal)',
sidebar: 'var(--shadow-sidebar)',
chat: 'var(--shadow-chat)',
'chat-input': 'var(--shadow-chat-input)',
'chat-active': 'var(--shadow-chat-active)',
'brand-soft': 'var(--shadow-brand-soft)',
'brand-active': 'var(--shadow-brand-active)',
'brand-strong': 'var(--shadow-brand-strong)',
},
},
},
plugins: [],
+3 -1
View File
@@ -13,6 +13,7 @@ export interface PaginatedResponse<T> {
page: number;
page_size: number;
total_pages: number;
trigger_counts?: Record<string, number>;
}
// Auth
@@ -106,7 +107,8 @@ export interface ChatMessage {
direction: 'incoming' | 'outgoing';
sender_id: string;
sender_name: string;
message_type: 'text' | 'image' | 'video';
/** text/image/video are peer messages; system is an official platform notice or trade card. */
message_type: 'text' | 'image' | 'video' | 'system';
content: string;
status: 'received' | 'sending' | 'sent' | 'failed';
sent_at: number;
+63
View File
@@ -98,6 +98,7 @@ type rawFields struct {
redReminder string
title string
detail string
orderRole string
updateKey string
contentType string
chatID string
@@ -121,8 +122,12 @@ func fieldsFromRaw(raw map[string]any) rawFields {
f.reminderURL = strAny(m10["reminderUrl"])
f.buyerID = strAny(m10["senderUserId"])
f.updateKey, f.contentType = extFields(strAny(m10["extJson"]))
f.orderRole = orderRoleFromTaskName(bizTaskName(strAny(m10["bizTag"])))
}
if contentJSON := nestedString(raw, "1", "6", "3", "5"); contentJSON != "" {
if role := extractOrderRoleFromContent(contentJSON); role != "" {
f.orderRole = role
}
if id := extractOrderIDFromContent(contentJSON); id != "" {
f.orderID = id
}
@@ -180,6 +185,9 @@ func fieldsFromRaw(raw map[string]any) rawFields {
}
func isOrderPaidEvent(f rawFields) bool {
if f.orderRole == "buyer" {
return false
}
return strings.Contains(f.text, "我已付款,等待你发货") ||
strings.Contains(f.text, "已付款,待发货") ||
strings.Contains(f.text, "记得及时发货") ||
@@ -279,6 +287,61 @@ var orderIDPatterns = []*regexp.Regexp{
regexp.MustCompile(`id=(\d{10,})`),
}
func extractOrderRoleFromContent(contentJSON string) string {
var c map[string]any
if json.Unmarshal([]byte(contentJSON), &c) != nil {
return ""
}
for _, path := range [][]string{
{"dxCard", "item", "main", "exContent", "button", "targetUrl"},
{"dxCard", "item", "main", "targetUrl"},
{"dynamicOperation", "changeContent", "dxCard", "item", "main", "exContent", "button", "targetUrl"},
} {
if role := orderRoleFromURL(nestedString(c, path...)); role != "" {
return role
}
}
return ""
}
func orderRoleFromURL(rawURL string) string {
if strings.TrimSpace(rawURL) == "" {
return ""
}
if strings.HasPrefix(rawURL, "fleamarket://") {
rawURL = "https://local.invalid/" + strings.TrimPrefix(rawURL, "fleamarket://")
}
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
switch strings.ToLower(strings.TrimSpace(u.Query().Get("role"))) {
case "seller", "buyer":
return strings.ToLower(strings.TrimSpace(u.Query().Get("role")))
default:
return ""
}
}
func bizTaskName(raw string) string {
var tag map[string]any
if json.Unmarshal([]byte(raw), &tag) != nil {
return ""
}
return strAny(tag["taskName"])
}
func orderRoleFromTaskName(taskName string) string {
switch {
case strings.Contains(taskName, "买家"):
return "buyer"
case strings.Contains(taskName, "卖家"):
return "seller"
default:
return ""
}
}
func matchOrderID(s string) string {
for _, re := range orderIDPatterns {
if m := re.FindStringSubmatch(s); len(m) == 2 {
+31
View File
@@ -80,6 +80,37 @@ func TestExtractTaskFromWS_OrderPaid(t *testing.T) {
}
}
func TestExtractTaskFromWS_BuyerOrderPaidIgnored(t *testing.T) {
raw := mustMap(t, `{
"1": {
"2": "63107041124@goofish",
"10": {
"redReminder": "等待卖家发货",
"reminderContent": "[我已付款,等待你发货]",
"senderUserId": "2222315258815",
"reminderUrl": "fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815&sid=63107041124"
},
"6": {"3": {"5": "{\"dxCard\":{\"item\":{\"main\":{\"targetUrl\":\"fleamarket://order_detail?id=3310145690545023994&role=buyer\"}}}}"}}
}
}`)
if task := ExtractTaskFromWS("acc1", "cookie", raw); task != nil {
t.Fatalf("买家订单不应进入卖家自动化和订单管理: %+v", task)
}
}
func TestExtractTaskFromWS_BuyerOrderPaidTaskNameIgnored(t *testing.T) {
raw := mustMap(t, `{
"1": {"2": "63107041124@goofish", "10": {
"bizTag": "{\"taskName\":\"付款完成待发货_买家\"}",
"redReminder": "等待卖家发货",
"reminderContent": "[我已付款,等待你发货]"
}}
}`)
if task := ExtractTaskFromWS("acc1", "cookie", raw); task != nil {
t.Fatalf("买家侧 taskName 不应进入卖家自动化和订单管理: %+v", task)
}
}
func mustMap(t *testing.T, s string) map[string]any {
t.Helper()
var m map[string]any
+82 -1
View File
@@ -65,6 +65,12 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
}
lastWrap, _ := conv["lastMessage"].(map[string]any)
last, _ := lastWrap["message"].(map[string]any)
// The conversation endpoint can return empty shells for notification
// recipients. The official web client does not render these as contacts;
// importing them creates fake users such as numeric IDs with “暂无消息”.
if len(last) == 0 {
continue
}
// reminderTitle belongs to the message presentation layer. Depending on
// the message type it may contain a nickname, an order-state prompt, or
// another card title. The official web client resolves conversation
@@ -72,10 +78,17 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
// as the session nickname.
peerName := ""
custom := map[string]any{}
extension := mapValue(last["extension"])
if content, ok := last["content"].(map[string]any); ok {
custom, _ = content["custom"].(map[string]any)
}
summary := cleanNilString(custom["summary"])
if summary == "" {
summary = cleanNilString(extension["reminderContent"])
}
if summary == "" {
summary = cleanNilString(extension["detailNotice"])
}
if summary == "" {
if encoded := cleanNilString(custom["data"]); encoded != "" {
var decoded map[string]any
@@ -240,6 +253,14 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
BuyerName: in.BuyerName, BuyerAvatar: extractString(in.Raw, "avatar", "avatarUrl", "senderAvatar"),
ItemID: in.ItemID, ItemTitle: extractString(in.Raw, "itemTitle", "title")}
messageType, content := extractMessageContent(in.Raw, in.Text)
if isOfficialSystemMessage(in.Raw, in.BuyerID, in.Text) {
messageType = "system"
if strings.TrimSuffix(strings.TrimSpace(in.BuyerID), "@goofish") == "1400" {
in.BuyerName = "闲小蜜"
session.BuyerName = "闲小蜜"
session.BuyerAvatar = xianxiaomiAvatar
}
}
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, true)
@@ -260,7 +281,7 @@ func (s *Service) RecordHistoryPage(ctx context.Context, accountID, chatID, myID
continue
}
session.CookieID, session.ChatID = accountID, chatID
if message.Direction == "incoming" {
if message.Direction == "incoming" && message.MessageType != "system" {
if session.BuyerID == "" {
session.BuyerID = message.SenderID
}
@@ -269,6 +290,12 @@ func (s *Service) RecordHistoryPage(ctx context.Context, accountID, chatID, myID
if err != nil {
return page, err
}
if message.MessageType == "system" {
if err := s.store.Chats.UpdateMessageType(ctx, accountID, message.MessageKey, "system"); err != nil {
return page, err
}
stored.MessageType = "system"
}
page.Messages = append(page.Messages, *stored)
}
return page, nil
@@ -307,6 +334,12 @@ func parseHistoryMessage(accountID, chatID, myID string, model map[string]any) (
}
}
messageType, content := extractMessageContent(rawContent, fallback)
if isOfficialSystemMessage(rawContent, senderID, fallback) {
messageType = "system"
if senderID == "1400" {
senderName = "闲小蜜"
}
}
if content == "" {
content = "[系统消息]"
}
@@ -406,6 +439,54 @@ func extractMessageContent(raw map[string]any, fallback string) (string, string)
return "text", strings.TrimSpace(fallback)
}
// isOfficialSystemMessage recognizes platform-generated IM content using the
// protocol metadata, rather than matching a growing list of Chinese prompts.
// contentType=14 is a platform notice and contentType=26 is an official trade
// card. User 1400 is 闲小蜜, whose messages are also not peer chat.
func isOfficialSystemMessage(raw map[string]any, senderID, fallback string) bool {
if strings.TrimSuffix(strings.TrimSpace(senderID), "@goofish") == "1400" {
return true
}
if contentType := findOfficialContentType(raw); contentType == "14" || contentType == "26" {
return true
}
return strings.TrimSpace(fallback) == "发来一条新消息"
}
// findOfficialContentType walks decoded history content as well as live WS
// envelopes. History stores the inner content JSON under custom.data, while
// live messages expose it under 1.6.3 or 1.10.extJson.
func findOfficialContentType(value any) string {
var found string
var walk func(any)
walk = func(current any) {
if found != "" {
return
}
switch typed := current.(type) {
case string:
var nested any
if json.Unmarshal([]byte(typed), &nested) == nil {
walk(nested)
}
case map[string]any:
if candidate := strings.TrimSpace(fmt.Sprint(typed["contentType"])); candidate == "14" || candidate == "26" {
found = candidate
return
}
for _, child := range typed {
walk(child)
}
case []any:
for _, child := range typed {
walk(child)
}
}
}
walk(value)
return found
}
func (s *Service) CreateOutgoing(ctx context.Context, session db.ChatSession, text string) (*db.ChatMessage, error) {
return s.CreateOutgoingMedia(ctx, session, "text", strings.TrimSpace(text))
}
+76
View File
@@ -58,6 +58,54 @@ func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
}
}
func TestRecordHistoryPageClassifiesOfficialCardsAsSystem(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
service := New(store)
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{"item":{"main":{"exContent":{"title":"我已拍下,待付款"}}}}}`))
body := map[string]any{"userMessageModels": []any{
map[string]any{"message": map[string]any{
"messageId": "official-card", "createAt": float64(3000),
"extension": map[string]any{"senderUserId": "peer@goofish", "reminderTitle": "买家已拍下,待付款"},
"content": map[string]any{"custom": map[string]any{"data": encoded, "summary": "[我已拍下,待付款]"}},
}},
}}
session := db.ChatSession{CookieID: "account-1", ChatID: "official", BuyerID: "peer", BuyerName: "真实昵称"}
if _, _, err := store.Chats.SaveMessage(context.Background(), session, db.ChatMessage{
MessageKey: "official-card", Direction: "incoming", SenderID: "peer", SenderName: "真实昵称",
MessageType: "text", Content: "[我已拍下,待付款]", Status: "received", SentAt: 3000,
}, false); err != nil {
t.Fatal(err)
}
page, err := service.RecordHistoryPage(context.Background(), "account-1", "official", "self", session, body)
if err != nil {
t.Fatal(err)
}
if len(page.Messages) != 1 || page.Messages[0].MessageType != "system" || page.Messages[0].Direction != "incoming" {
t.Fatalf("official card was not classified as system: %+v", page.Messages)
}
if page.Messages[0].SenderName != "真实昵称" {
t.Fatalf("history sender metadata unexpectedly changed: %+v", page.Messages[0])
}
}
func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
service := New(store)
message, inserted, err := service.RecordIncoming(context.Background(), Incoming{
AccountID: "account-1", ChatID: "xiaomi", BuyerID: "1400@goofish",
BuyerName: "闲小蜜发来一条新消息", Text: "邀您填写售后问卷",
Raw: map[string]any{"messageId": "xiaomi-1"},
})
if err != nil || !inserted {
t.Fatalf("record xianxiaomi message: message=%+v inserted=%v err=%v", message, inserted, err)
}
if message.MessageType != "system" || message.SenderName != "闲小蜜" {
t.Fatalf("xianxiaomi message was not classified: %+v", message)
}
}
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
@@ -124,6 +172,34 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
}
}
func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
service := New(store)
body := map[string]any{"userConvs": []any{
map[string]any{"singleChatUserConversation": map[string]any{
"singleChatConversation": map[string]any{"cid": "empty@goofish", "pairFirst": "self@goofish", "pairSecond": "69@goofish"},
}},
map[string]any{"singleChatUserConversation": map[string]any{
"singleChatConversation": map[string]any{"cid": "system@goofish", "pairFirst": "self@goofish", "pairSecond": "1400@goofish"},
"lastMessage": map[string]any{"message": map[string]any{
"createAt": float64(100), "reminderContent": "邀您填写售后问卷",
}},
}},
}}
if _, err := service.RecordConversationPage(context.Background(), "account-1", "self", body); err != nil {
t.Fatal(err)
}
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
rows, err := store.Chats.ListSessions(context.Background(), owner.ID, "account-1", 20)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].ChatID != "system" {
t.Fatalf("empty conversation shell was imported: %+v", rows)
}
}
func TestDeleteEmptySessionsRemovesGhostsButKeepsRealConversation(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
+74 -40
View File
@@ -143,27 +143,8 @@ type AutomationRuleListFilter struct {
Offset int
}
// AutomationActionInput 是创建动作的输入。
type AutomationActionInput struct {
ActionType string
CardID int64
DeliveryCount int
MessageTemplate string
DelaySeconds int
ConfigJSON string
Enabled bool
SortOrder int
}
// ListForUser 返回用户下全部自动化规则和动作。
func (a *AutomationRules) ListForUser(ctx context.Context, userID int64) ([]AutomationRule, error) {
rules, _, err := a.ListPageForUser(ctx, AutomationRuleListFilter{UserID: userID})
return rules, err
}
// ListPageForUser 按用户隔离筛选并分页查询自动化规则和动作。
func (a *AutomationRules) ListPageForUser(ctx context.Context, f AutomationRuleListFilter) ([]AutomationRule, int, error) {
where := []string{"r.user_id=?"}
func automationRuleWhere(f AutomationRuleListFilter) (string, []any) {
where := []string{"r.user_id=?", "r.deleted_at IS NULL"}
args := []any{f.UserID}
if f.CookieID != "" {
where = append(where, "r.cookie_id=?")
@@ -184,13 +165,36 @@ func (a *AutomationRules) ListPageForUser(ctx context.Context, f AutomationRuleL
OR LOWER(COALESCE(i.item_title,'')) LIKE ?)`)
args = append(args, pattern, pattern, pattern)
}
whereSQL := strings.Join(where, " AND ")
return strings.Join(where, " AND "), args
}
// AutomationActionInput 是创建动作的输入。
type AutomationActionInput struct {
ActionType string
CardID int64
DeliveryCount int
MessageTemplate string
DelaySeconds int
ConfigJSON string
Enabled bool
SortOrder int
}
// ListForUser 返回用户下全部自动化规则和动作。
func (a *AutomationRules) ListForUser(ctx context.Context, userID int64) ([]AutomationRule, error) {
rules, _, err := a.ListPageForUser(ctx, AutomationRuleListFilter{UserID: userID})
return rules, err
}
// ListPageForUser 按用户隔离筛选并分页查询自动化规则和动作。
func (a *AutomationRules) ListPageForUser(ctx context.Context, f AutomationRuleListFilter) ([]AutomationRule, int, error) {
whereSQL, args := automationRuleWhere(f)
var total int
if err := a.DB.QueryRowContext(ctx, `
SELECT COUNT(*)
FROM automation_rules r
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
WHERE `+whereSQL, args...).Scan(&total); err != nil {
return nil, 0, err
}
@@ -205,7 +209,7 @@ SELECT COUNT(*)
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
r.priority,r.config_json,r.created_at,r.updated_at
FROM automation_rules r
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
WHERE `+whereSQL+`
ORDER BY r.created_at DESC,r.id DESC`+limitSQL, queryArgs...)
if err != nil {
@@ -231,6 +235,32 @@ SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.t
return out, total, rows.Err()
}
// CountByTriggerForUser 返回同一筛选条件下各触发类型的规则数量。
// 该统计不受分页影响,确保页面汇总与 total 使用同一数据集。
func (a *AutomationRules) CountByTriggerForUser(ctx context.Context, f AutomationRuleListFilter) (map[string]int, error) {
whereSQL, args := automationRuleWhere(f)
rows, err := a.DB.QueryContext(ctx, `
SELECT r.trigger_type, COUNT(*)
FROM automation_rules r
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
WHERE `+whereSQL+`
GROUP BY r.trigger_type`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
counts := map[string]int{}
for rows.Next() {
var triggerType string
var count int
if err := rows.Scan(&triggerType, &count); err != nil {
return nil, err
}
counts[triggerType] = count
}
return counts, rows.Err()
}
// Match 查询某事件可触发的规则。商品级规则存在时只返回商品级规则;
// 没有商品级规则时才回退到账号级规则,避免两层规则叠加导致重复发货。
func (a *AutomationRules) Match(ctx context.Context, cookieID, itemID, triggerType string) ([]AutomationRule, error) {
@@ -257,8 +287,8 @@ func (a *AutomationRules) Get(ctx context.Context, ruleID int64) (*AutomationRul
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
r.priority,r.config_json,r.created_at,r.updated_at
FROM automation_rules r
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
WHERE r.id=?`, ruleID).Scan(&rule.ID, &rule.UserID, &rule.CookieID, &rule.ItemID, &rule.ItemTitle,
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
WHERE r.id=? AND r.deleted_at IS NULL`, ruleID).Scan(&rule.ID, &rule.UserID, &rule.CookieID, &rule.ItemID, &rule.ItemTitle,
&rule.Name, &rule.TriggerType, &enabled, &rule.Priority, &rule.ConfigJSON, &rule.CreatedAt, &rule.UpdatedAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
@@ -276,12 +306,13 @@ func (a *AutomationRules) matchScope(ctx context.Context, cookieID, itemID, trig
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
r.priority,r.config_json,r.created_at,r.updated_at
FROM automation_rules r
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
WHERE r.enabled=1
AND r.cookie_id=?
AND r.trigger_type=?
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
WHERE r.deleted_at IS NULL
AND r.enabled=1
AND r.cookie_id=?
AND r.trigger_type=?
AND r.item_id=?
ORDER BY r.priority ASC, r.id ASC`, cookieID, triggerType, itemID)
ORDER BY r.priority ASC, r.id ASC`, cookieID, triggerType, itemID)
if err != nil {
return nil, err
}
@@ -332,7 +363,7 @@ func (a *AutomationRules) Update(ctx context.Context, userID, ruleID int64, in A
res, err := tx.ExecContext(ctx, `
UPDATE automation_rules
SET cookie_id=?,item_id=?,name=?,trigger_type=?,enabled=?,priority=?,config_json=?,updated_at=CURRENT_TIMESTAMP
WHERE id=? AND user_id=?`,
WHERE id=? AND user_id=? AND deleted_at IS NULL`,
in.CookieID, in.ItemID, in.Name, in.TriggerType, boolToInt(in.Enabled), in.Priority, validJSON(in.ConfigJSON), ruleID, userID)
if err != nil {
return err
@@ -351,10 +382,11 @@ UPDATE automation_rules
return tx.Commit()
}
// Delete 删除规则。
// Delete 逻辑删除规则,保留动作和执行记录以便审计;逻辑删除后不再出现在规则列表和匹配结果中。
func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) error {
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_rules
WHERE id=? AND user_id=? AND NOT EXISTS (
res, err := a.DB.ExecContext(ctx, `UPDATE automation_rules
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
WHERE id=? AND user_id=? AND deleted_at IS NULL AND NOT EXISTS (
SELECT 1 FROM automation_runs ar WHERE ar.rule_id=automation_rules.id
AND (ar.status IN ('running','needs_review') OR (ar.status='failed' AND ar.sent_count=0 AND ar.attempt_count<3)))`, ruleID, userID)
if err != nil {
@@ -362,7 +394,7 @@ func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) erro
}
if n, _ := res.RowsAffected(); n == 0 {
var exists int
if err := a.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_rules WHERE id=? AND user_id=?`, ruleID, userID).Scan(&exists); err != nil {
if err := a.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_rules WHERE id=? AND user_id=? AND deleted_at IS NULL`, ruleID, userID).Scan(&exists); err != nil {
return err
}
if exists > 0 {
@@ -667,7 +699,7 @@ func (a *AutomationRules) ListIssues(ctx context.Context, userID int64) ([]Autom
ar.action_cursor,ar.sent_count,ar.updated_at,ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0)
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
LEFT JOIN automation_rules r ON r.id=ar.rule_id
WHERE c.user_id=? AND ar.status='needs_review' ORDER BY ar.updated_at DESC,ar.id DESC`, userID)
WHERE c.user_id=? AND ar.status='needs_review' AND r.deleted_at IS NULL ORDER BY ar.updated_at DESC,ar.id DESC`, userID)
if err != nil {
return nil, nil, err
}
@@ -715,7 +747,7 @@ func (a *AutomationRules) ResolveRunIssue(ctx context.Context, userID, runID int
err := a.DB.QueryRowContext(ctx, `SELECT ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0),ar.sent_count,ar.error_message
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
LEFT JOIN automation_rules r ON r.id=ar.rule_id
WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=?`, runID, userID).
WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=? AND r.deleted_at IS NULL`, runID, userID).
Scan(&rawEventJSON, &actionStarted, &ruleEnabled, &sentCount, &errorMessage)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
@@ -974,12 +1006,14 @@ SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_stat
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
created_at,updated_at
FROM orders o
WHERE o.system_shipped=1
WHERE o.system_shipped=1
AND o.deleted_at IS NULL
AND COALESCE(o.buyer_reviewed_at,'')=''
AND COALESCE(o.chat_id,'')<>''
AND EXISTS (SELECT 1 FROM automation_rules r
WHERE r.cookie_id=o.cookie_id AND r.trigger_type='review_missing_timeout'
AND r.enabled=1 AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+`
AND r.deleted_at IS NULL AND r.enabled=1
AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+`
ORDER BY o.order_id ASC
LIMIT ?`, args...)
if err != nil {
+8
View File
@@ -204,6 +204,14 @@ func TestAutomation_UpdateDelete(t *testing.T) {
if len(rules) != 0 {
t.Fatalf("Delete 后 len=%d want 0", len(rules))
}
var deletedAt string
var enabled int
if err := s.DB.QueryRowContext(ctx, `SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&deletedAt, &enabled); err != nil {
t.Fatalf("逻辑删除后规则原始行不存在: %v", err)
}
if deletedAt == "" || enabled != 0 {
t.Fatalf("规则未逻辑删除并禁用: deleted_at=%q enabled=%d", deletedAt, enabled)
}
// 重复 Delete → ErrNotFound。
if err := s.Automation.Delete(ctx, uid, ruleID); !errors.Is(err, ErrNotFound) {
t.Fatalf("重复 Delete 应 ErrNotFound, got %v", err)
+9
View File
@@ -110,6 +110,7 @@ func (s *ChatStore) LatestUnmaskedPeerName(ctx context.Context, cookieID, chatID
var name string
err := s.DB.QueryRowContext(ctx, `SELECT sender_name FROM chat_messages
WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND sender_name<>'' AND sender_name NOT LIKE '%***%'
AND message_type<>'system'
AND sender_name<>content AND sender_name NOT IN ('交易消息','系统消息','卡片消息','我完成了评价','对方完成了评价',
'快给ta一个评价吧~','卖家已发货','买家已付款','买家已确认收货','等待您发货','超时未付款,系统关闭了订单','邀您填写售后问卷')
ORDER BY sent_at DESC,id DESC LIMIT 1`, cookieID, chatID).Scan(&name)
@@ -197,6 +198,14 @@ func (s *ChatStore) GetMessageByKey(ctx context.Context, cookieID, key string) (
return &m, err
}
// UpdateMessageType refreshes the classification of an already persisted
// message when a later history response exposes richer protocol metadata.
func (s *ChatStore) UpdateMessageType(ctx context.Context, cookieID, key, messageType string) error {
_, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET message_type=?
WHERE cookie_id=? AND message_key=?`, messageType, cookieID, key)
return err
}
func (s *ChatStore) ListSessions(ctx context.Context, userID int64, cookieID string, limit int) ([]ChatSession, error) {
if limit <= 0 || limit > 500 {
limit = 200
+3 -3
View File
@@ -53,7 +53,7 @@ func (i *Items) Get(ctx context.Context, cookieID, itemID string) (*ItemInfo, er
err := i.DB.QueryRowContext(ctx,
`SELECT id, cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail,
is_multi_spec, multi_quantity_delivery
FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(
FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(
&it.ID, &it.CookieID, &it.ItemID, &title, &desc, &cat,
&price, &detail, &isMulti, &multiQty)
if err != nil {
@@ -75,7 +75,7 @@ func (i *Items) Get(ctx context.Context, cookieID, itemID string) (*ItemInfo, er
// IsMultiSpec 是否多规格商品。
func (i *Items) IsMultiSpec(ctx context.Context, cookieID, itemID string) bool {
var v int
err := i.DB.QueryRowContext(ctx, `SELECT is_multi_spec FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(&v)
err := i.DB.QueryRowContext(ctx, `SELECT is_multi_spec FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(&v)
if err != nil {
return false
}
@@ -85,7 +85,7 @@ func (i *Items) IsMultiSpec(ctx context.Context, cookieID, itemID string) bool {
// MultiQuantityDelivery 是否开启多数量发货。
func (i *Items) MultiQuantityDelivery(ctx context.Context, cookieID, itemID string) bool {
var v int
err := i.DB.QueryRowContext(ctx, `SELECT multi_quantity_delivery FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(&v)
err := i.DB.QueryRowContext(ctx, `SELECT multi_quantity_delivery FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(&v)
if err != nil {
return false
}
+119 -6
View File
@@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
"strconv"
"strings"
)
// ---- 关键字 CRUD ----
@@ -520,13 +521,19 @@ type ItemInfoRow struct {
MultiQuantityDelivery bool
}
// ItemSyncResult 是一次远端商品全集同步的结果。
type ItemSyncResult struct {
Saved int
Deleted int
}
// AllForCookie 取某账号全部商品。
func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRow, error) {
rows, err := i.DB.QueryContext(ctx,
`SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''),
COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''),
is_multi_spec, COALESCE(multi_quantity_delivery,0)
FROM item_info WHERE cookie_id=? ORDER BY id DESC`, cookieID)
FROM item_info WHERE cookie_id=? AND deleted_at IS NULL ORDER BY id DESC`, cookieID)
if err != nil {
return nil, err
}
@@ -560,6 +567,7 @@ func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error {
"item_detail": "EXCLUDED.item_detail",
"is_multi_spec": "EXCLUDED.is_multi_spec",
"multi_quantity_delivery": "EXCLUDED.multi_quantity_delivery",
"deleted_at": "NULL",
"updated_at": "CURRENT_TIMESTAMP",
}),
r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription),
@@ -577,6 +585,95 @@ func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) e
return i.upsertBasic(ctx, tx, r)
}
// SyncFromRemote 将远端商品全集同步到本地。
//
// 远端列表只提供商品基础信息,因此保留本地的描述和发货配置;基础字段
// (标题、分类、价格、详情)由远端非空值覆盖。整个 reconcile 在一个事务内
// 完成,只有在全部远端商品写入成功后,才会逻辑删除本次全集中不存在的本地商品及其商品级自动化规则。
func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []ItemInfoRow) (ItemSyncResult, error) {
cookieID = strings.TrimSpace(cookieID)
if cookieID == "" {
return ItemSyncResult{}, errors.New("cookie_id 不能为空")
}
remoteIDs := make(map[string]struct{}, len(rows))
validRows := make([]ItemInfoRow, 0, len(rows))
for _, row := range rows {
row.CookieID = cookieID
row.ItemID = strings.TrimSpace(row.ItemID)
if row.ItemID == "" {
continue
}
if _, exists := remoteIDs[row.ItemID]; exists {
continue
}
remoteIDs[row.ItemID] = struct{}{}
validRows = append(validRows, row)
}
tx, err := i.DB.BeginTx(ctx, nil)
if err != nil {
return ItemSyncResult{}, err
}
rollback := func(err error) (ItemSyncResult, error) {
_ = tx.Rollback()
return ItemSyncResult{}, err
}
for index := range validRows {
if err := i.UpsertBasicTx(ctx, tx, &validRows[index]); err != nil {
return rollback(err)
}
if validRows[index].IsMultiSpec {
if _, err := tx.ExecContext(ctx,
`UPDATE item_info SET is_multi_spec=? WHERE cookie_id=? AND item_id=?`,
boolToInt(true), cookieID, validRows[index].ItemID); err != nil {
return rollback(err)
}
}
}
args := make([]any, 0, len(remoteIDs)+1)
args = append(args, cookieID)
deleteQuery := `UPDATE item_info SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND deleted_at IS NULL`
if len(remoteIDs) > 0 {
placeholders := make([]string, 0, len(remoteIDs))
for itemID := range remoteIDs {
placeholders = append(placeholders, "?")
args = append(args, itemID)
}
deleteQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
}
deletedResult, err := tx.ExecContext(ctx, deleteQuery, args...)
if err != nil {
return rollback(err)
}
deleted, err := deletedResult.RowsAffected()
if err != nil {
return rollback(err)
}
ruleArgs := make([]any, 0, len(remoteIDs)+1)
ruleArgs = append(ruleArgs, cookieID)
ruleQuery := `UPDATE automation_rules
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id<>'' AND deleted_at IS NULL`
if len(remoteIDs) > 0 {
placeholders := make([]string, 0, len(remoteIDs))
for itemID := range remoteIDs {
placeholders = append(placeholders, "?")
ruleArgs = append(ruleArgs, itemID)
}
ruleQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
}
if _, err := tx.ExecContext(ctx, ruleQuery, ruleArgs...); err != nil {
return rollback(err)
}
if err := tx.Commit(); err != nil {
return ItemSyncResult{}, err
}
return ItemSyncResult{Saved: len(validRows), Deleted: int(deleted)}, nil
}
func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRow) error {
// 三种数据库的条件 upsert:非空才覆盖,空值保留旧值。
// SQLite/Postgres 用 EXCLUDED.col 引用插入值;MySQL 用 VALUES(col)。
@@ -589,6 +686,7 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo
item_category=CASE WHEN VALUES(item_category) IS NOT NULL AND VALUES(item_category) != '' THEN VALUES(item_category) ELSE item_info.item_category END,
item_price=CASE WHEN VALUES(item_price) IS NOT NULL AND VALUES(item_price) != '' THEN VALUES(item_price) ELSE item_info.item_price END,
item_detail=CASE WHEN VALUES(item_detail) IS NOT NULL AND VALUES(item_detail) != '' THEN VALUES(item_detail) ELSE item_info.item_detail END,
deleted_at=NULL,
updated_at=CURRENT_TIMESTAMP`
default:
conflictClause = ` ON CONFLICT(cookie_id, item_id) DO UPDATE SET
@@ -597,6 +695,7 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo
item_category=CASE WHEN EXCLUDED.item_category IS NOT NULL AND EXCLUDED.item_category != '' THEN EXCLUDED.item_category ELSE item_info.item_category END,
item_price=CASE WHEN EXCLUDED.item_price IS NOT NULL AND EXCLUDED.item_price != '' THEN EXCLUDED.item_price ELSE item_info.item_price END,
item_detail=CASE WHEN EXCLUDED.item_detail IS NOT NULL AND EXCLUDED.item_detail != '' THEN EXCLUDED.item_detail ELSE item_info.item_detail END,
deleted_at=NULL,
updated_at=CURRENT_TIMESTAMP`
}
_, err := execer.ExecContext(ctx,
@@ -608,16 +707,30 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo
return err
}
// Delete 删除商品。
// Delete 逻辑删除商品及其商品级自动化规则,保留历史数据以便审计和恢复。
func (i *Items) Delete(ctx context.Context, cookieID, itemID string) error {
_, err := i.DB.ExecContext(ctx, `DELETE FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID)
return err
tx, err := i.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `UPDATE item_info
SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `UPDATE automation_rules
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
return err
}
return tx.Commit()
}
// SetMultiSpec 设置多规格开关。
func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bool) error {
_, err := i.DB.ExecContext(ctx,
`UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=?`,
`UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
boolToInt(on), cookieID, itemID)
return err
}
@@ -625,7 +738,7 @@ func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bo
// SetMultiQuantity 设置多数量发货开关。
func (i *Items) SetMultiQuantity(ctx context.Context, cookieID, itemID string, on bool) error {
_, err := i.DB.ExecContext(ctx,
`UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=?`,
`UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
boolToInt(on), cookieID, itemID)
return err
}
+158
View File
@@ -2,6 +2,7 @@ package db
import (
"context"
"database/sql"
"testing"
)
@@ -104,3 +105,160 @@ func TestExtraRepositoriesCRUD(t *testing.T) {
t.Fatal(err)
}
}
func TestItemsSyncFromRemoteReconcilesAndPreservesLocalSettings(t *testing.T) {
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
ok, err := store.Users.Create(ctx, "sync-user", "sync@example.com", "password")
if err != nil || !ok {
t.Fatalf("create test user: ok=%v err=%v", ok, err)
}
user, err := store.Users.GetByUsername(ctx, "sync-user")
if err != nil {
t.Fatal(err)
}
if err := store.Cookies.Save(ctx, "acc1", "unb=1", user.ID); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &ItemInfoRow{
CookieID: "acc1", ItemID: "existing", ItemTitle: "旧标题", ItemDescription: "本地描述", ItemPrice: "¥9.90",
}); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiSpec(ctx, "acc1", "existing", true); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiQuantity(ctx, "acc1", "existing", true); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &ItemInfoRow{CookieID: "acc1", ItemID: "deleted"}); err != nil {
t.Fatal(err)
}
ruleID, err := store.Automation.Create(ctx, AutomationRuleInput{
UserID: user.ID, CookieID: "acc1", ItemID: "deleted", Name: "删除商品规则",
TriggerType: "paid", Enabled: true, Priority: 100,
Actions: []AutomationActionInput{{ActionType: "send_msg", MessageTemplate: "hello", Enabled: true, SortOrder: 1}},
})
if err != nil {
t.Fatal(err)
}
result, err := store.Items.SyncFromRemote(ctx, "acc1", []ItemInfoRow{
{CookieID: "wrong-cookie", ItemID: "existing", ItemTitle: "新标题", ItemPrice: "¥19.90", IsMultiSpec: true},
{ItemID: "new", ItemTitle: "新商品", ItemPrice: "¥3.00"},
})
if err != nil {
t.Fatal(err)
}
if result.Saved != 2 || result.Deleted != 1 {
t.Fatalf("sync result=%+v, want saved=2 deleted=1", result)
}
items, err := store.Items.AllForCookie(ctx, "acc1")
if err != nil {
t.Fatal(err)
}
if len(items) != 2 {
t.Fatalf("items=%+v, want 2 rows", items)
}
item, err := store.Items.Get(ctx, "acc1", "existing")
if err != nil {
t.Fatal(err)
}
if item.ItemTitle != "新标题" || item.ItemPrice != "¥19.90" || item.ItemDescription != "本地描述" ||
!item.IsMultiSpec || !item.MultiQuantityDelivery {
t.Fatalf("existing item was not updated/preserved: %+v", item)
}
if _, err := store.Items.Get(ctx, "acc1", "deleted"); err != ErrNotFound {
t.Fatalf("deleted item should be hidden from active lookup: err=%v", err)
}
var itemDeletedAt sql.NullString
if err := store.DB.QueryRowContext(ctx,
`SELECT deleted_at FROM item_info WHERE cookie_id=? AND item_id=?`, "acc1", "deleted").Scan(&itemDeletedAt); err != nil {
t.Fatalf("商品逻辑删除后原始行不存在: %v", err)
}
if !itemDeletedAt.Valid || itemDeletedAt.String == "" {
t.Fatalf("商品 deleted_at 未写入: %#v", itemDeletedAt)
}
var ruleDeletedAt sql.NullString
var ruleEnabled int
if err := store.DB.QueryRowContext(ctx,
`SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&ruleDeletedAt, &ruleEnabled); err != nil {
t.Fatalf("关联规则逻辑删除后原始行不存在: %v", err)
}
if !ruleDeletedAt.Valid || ruleDeletedAt.String == "" || ruleEnabled != 0 {
t.Fatalf("关联规则未逻辑删除并禁用: deleted_at=%#v enabled=%d", ruleDeletedAt, ruleEnabled)
}
rules, err := store.Automation.ListForUser(ctx, user.ID)
if err != nil {
t.Fatal(err)
}
if len(rules) != 0 {
t.Fatalf("已删除商品的规则不应出现在管理列表: %#v", rules)
}
matched, err := store.Automation.Match(ctx, "acc1", "deleted", "paid")
if err != nil {
t.Fatal(err)
}
if len(matched) != 0 {
t.Fatalf("已删除商品的规则不应再匹配: %#v", matched)
}
// 商品再次出现在远端时只恢复商品,不自动恢复已删除规则,避免旧规则误复活。
if _, err := store.Items.SyncFromRemote(ctx, "acc1", []ItemInfoRow{{ItemID: "existing"}, {ItemID: "deleted"}}); err != nil {
t.Fatal(err)
}
if _, err := store.Items.Get(ctx, "acc1", "deleted"); err != nil {
t.Fatalf("商品重新同步后应恢复商品记录: %v", err)
}
rules, err = store.Automation.ListForUser(ctx, user.ID)
if err != nil {
t.Fatal(err)
}
if len(rules) != 0 {
t.Fatalf("商品恢复后不应自动恢复旧规则: %#v", rules)
}
}
func TestItemsDeleteSoftDeletesRelatedAutomationRule(t *testing.T) {
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
if ok, err := store.Users.Create(ctx, "item-delete-user", "item-delete@example.com", "password"); err != nil || !ok {
t.Fatalf("create test user: ok=%v err=%v", ok, err)
}
user, err := store.Users.GetByUsername(ctx, "item-delete-user")
if err != nil {
t.Fatal(err)
}
if err := store.Cookies.Save(ctx, "item-delete-cookie", "unb=1", user.ID); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &ItemInfoRow{CookieID: "item-delete-cookie", ItemID: "item-1", ItemTitle: "待删除商品"}); err != nil {
t.Fatal(err)
}
ruleID, err := store.Automation.Create(ctx, AutomationRuleInput{
UserID: user.ID, CookieID: "item-delete-cookie", ItemID: "item-1", Name: "商品规则",
TriggerType: "paid", Enabled: true, Priority: 100,
Actions: []AutomationActionInput{{ActionType: "send_msg", MessageTemplate: "hello", Enabled: true, SortOrder: 1}},
})
if err != nil {
t.Fatal(err)
}
if err := store.Items.Delete(ctx, "item-delete-cookie", "item-1"); err != nil {
t.Fatal(err)
}
var itemDeletedAt, ruleDeletedAt string
var ruleEnabled int
if err := store.DB.QueryRowContext(ctx, `SELECT deleted_at FROM item_info WHERE cookie_id=? AND item_id=?`, "item-delete-cookie", "item-1").Scan(&itemDeletedAt); err != nil {
t.Fatalf("商品行未保留: %v", err)
}
if err := store.DB.QueryRowContext(ctx, `SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&ruleDeletedAt, &ruleEnabled); err != nil {
t.Fatalf("规则行未保留: %v", err)
}
if itemDeletedAt == "" || ruleDeletedAt == "" || ruleEnabled != 0 {
t.Fatalf("商品和规则未完成逻辑删除: item_deleted_at=%q rule_deleted_at=%q enabled=%d", itemDeletedAt, ruleDeletedAt, ruleEnabled)
}
}
+11 -2
View File
@@ -29,10 +29,13 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
{"orders", "system_shipped"},
{"orders", "receiver_city"},
{"orders", "version"},
{"orders", "deleted_at"},
{"cards", "image_url"},
{"cards", "delay_seconds"},
{"keywords", "item_id"},
{"item_info", "multi_quantity_delivery"},
{"item_info", "deleted_at"},
{"automation_rules", "deleted_at"},
{"default_replies", "reply_once"},
{"default_reply_records", "status"},
{"default_reply_records", "text_sent"},
@@ -125,8 +128,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
t.Fatalf("goose dialect: %v", err)
}
goose.SetBaseFS(migrationsFS)
// 依次回滚最新版本到 14,再整体升级。
for i := 0; i < 12; i++ {
// 依次回滚最新版本到 13,再整体升级。
for i := 0; i < 14; i++ {
if err := goose.Down(d, "migrations/sqlite"); err != nil {
t.Fatalf("down migration #%d: %v", i+1, err)
}
@@ -146,6 +149,12 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
if columnExists(t, d, "item_publish_batch_rows", "category_json") {
t.Fatal("item_publish_batch_rows.category_json should be removed after migration 23 down")
}
if columnExists(t, d, "item_info", "deleted_at") || columnExists(t, d, "automation_rules", "deleted_at") {
t.Fatal("soft-delete columns should be removed after migration 26 down")
}
if columnExists(t, d, "orders", "deleted_at") {
t.Fatal("orders.deleted_at should be removed after migration 27 down")
}
for _, table := range []string{"account_task_settings", "account_task_runs", "chat_sessions", "chat_messages"} {
if tableExists(t, d, table) {
t.Fatalf("table should be removed after migration 24 down: %s", table)
@@ -0,0 +1,11 @@
-- +goose Up
ALTER TABLE item_info ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
ALTER TABLE automation_rules ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX idx_item_info_active ON item_info(cookie_id, deleted_at);
CREATE INDEX idx_automation_rules_active_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, deleted_at);
-- +goose Down
DROP INDEX idx_automation_rules_active_match ON automation_rules;
DROP INDEX idx_item_info_active ON item_info;
ALTER TABLE automation_rules DROP COLUMN deleted_at;
ALTER TABLE item_info DROP COLUMN deleted_at;
@@ -0,0 +1,7 @@
-- +goose Up
ALTER TABLE orders ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX idx_orders_active ON orders(cookie_id, deleted_at);
-- +goose Down
DROP INDEX idx_orders_active ON orders;
ALTER TABLE orders DROP COLUMN deleted_at;
@@ -0,0 +1,11 @@
-- +goose Up
ALTER TABLE item_info ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
ALTER TABLE automation_rules ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX idx_item_info_active ON item_info(cookie_id, deleted_at);
CREATE INDEX idx_automation_rules_active_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, deleted_at);
-- +goose Down
DROP INDEX IF EXISTS idx_automation_rules_active_match;
DROP INDEX IF EXISTS idx_item_info_active;
ALTER TABLE automation_rules DROP COLUMN deleted_at;
ALTER TABLE item_info DROP COLUMN deleted_at;
@@ -0,0 +1,7 @@
-- +goose Up
ALTER TABLE orders ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX idx_orders_active ON orders(cookie_id, deleted_at);
-- +goose Down
DROP INDEX IF EXISTS idx_orders_active;
ALTER TABLE orders DROP COLUMN deleted_at;
@@ -0,0 +1,11 @@
-- +goose Up
ALTER TABLE item_info ADD COLUMN deleted_at TIMESTAMP NULL;
ALTER TABLE automation_rules ADD COLUMN deleted_at TIMESTAMP NULL;
CREATE INDEX idx_item_info_active ON item_info(cookie_id, deleted_at);
CREATE INDEX idx_automation_rules_active_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, deleted_at);
-- +goose Down
DROP INDEX IF EXISTS idx_automation_rules_active_match;
DROP INDEX IF EXISTS idx_item_info_active;
ALTER TABLE automation_rules DROP COLUMN deleted_at;
ALTER TABLE item_info DROP COLUMN deleted_at;
@@ -0,0 +1,7 @@
-- +goose Up
ALTER TABLE orders ADD COLUMN deleted_at TIMESTAMP NULL;
CREATE INDEX idx_orders_active ON orders(cookie_id, deleted_at);
-- +goose Down
DROP INDEX IF EXISTS idx_orders_active;
ALTER TABLE orders DROP COLUMN deleted_at;
+4 -1
View File
@@ -771,7 +771,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
t.Fatalf("set goose dialect: %v", err)
}
goose.SetBaseFS(migrationsFS)
for i := 0; i < 12; i++ {
for i := 0; i < 14; i++ {
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
t.Fatalf("migration down #%d: %v", i+1, err)
}
@@ -816,6 +816,9 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
{"automation_runs", "action_started"},
{"account_tokens", "cookie_fingerprint"},
{"item_publish_batch_rows", "category_json"},
{"item_info", "deleted_at"},
{"automation_rules", "deleted_at"},
{"orders", "deleted_at"},
{"account_task_settings", "auto_rate_enabled"},
{"account_task_runs", "run_key"},
{"chat_sessions", "unread_count"},
+19 -4
View File
@@ -130,6 +130,18 @@ func (o *Orders) UpsertTx(ctx context.Context, tx *sql.Tx, orderID string, opts
return upsertOrder(ctx, tx, o.Dialect, orderID, opts)
}
// SoftDelete 将订单标记为逻辑删除,保留历史数据供审计和后续恢复。
func (o *Orders) SoftDelete(ctx context.Context, orderID string) (bool, error) {
result, err := o.DB.ExecContext(ctx,
`UPDATE orders SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
WHERE order_id=? AND deleted_at IS NULL`, orderID)
if err != nil {
return false, err
}
changed, err := result.RowsAffected()
return changed > 0, err
}
func upsertOrder(ctx context.Context, execer sqlQueryExecer, dialect Dialect, orderID string, opts OrderUpsertOpts) error {
if orderID == "" {
return errors.New("order_id 不能为空")
@@ -152,11 +164,11 @@ func upsertOrder(ctx context.Context, execer sqlQueryExecer, dialect Dialect, or
}
for attempt := 0; attempt < maxOrderUpsertRetries; attempt++ {
var existingCookie, existingStatus sql.NullString
var existingCookie, existingStatus, deletedAt sql.NullString
var version int
if err := execer.QueryRowContext(ctx,
`SELECT cookie_id,order_status,version FROM orders WHERE order_id=?`, orderID).
Scan(&existingCookie, &existingStatus, &version); err != nil {
`SELECT cookie_id,order_status,version,deleted_at FROM orders WHERE order_id=?`, orderID).
Scan(&existingCookie, &existingStatus, &version, &deletedAt); err != nil {
return err
}
if opts.CookieID != "" && existingCookie.Valid && existingCookie.String != "" && existingCookie.String != opts.CookieID {
@@ -168,6 +180,9 @@ func upsertOrder(ctx context.Context, execer sqlQueryExecer, dialect Dialect, or
current.OrderStatus = ""
}
set, args := orderUpsertAssignments(current)
if deletedAt.Valid && deletedAt.String != "" {
set = append(set, "deleted_at=NULL")
}
if len(set) == 0 {
return nil
}
@@ -296,7 +311,7 @@ func (o *Orders) Get(ctx context.Context, orderID string) (*Order, error) {
COALESCE(paid_at,''),COALESCE(shipped_at,''),COALESCE(completed_at,''),
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
created_at, updated_at
FROM orders WHERE order_id=?`, orderID).Scan(
FROM orders WHERE order_id=? AND deleted_at IS NULL`, orderID).Scan(
&ord.OrderID, &itemID, &buyerID, &specName, &specValue, &qty, &amount,
&status, &cookieID, &isBargain, &receiverName, &receiverPhone, &receiverAddr,
&receiverCity, &version, &chatID, &sysShipped, &paidAt, &shippedAt, &completedAt,
+25
View File
@@ -30,6 +30,31 @@ func TestOrdersByCookiePageScansBeyondLegacyLimit(t *testing.T) {
}
}
func TestOrdersSoftDeleteMissingForCookie(t *testing.T) {
s, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
_, cid := seedAccount(t, s)
for _, orderID := range []string{"seller-order", "buyer-order"} {
if err := s.Orders.Upsert(ctx, orderID, OrderUpsertOpts{CookieID: cid, OrderStatus: "pending_ship"}); err != nil {
t.Fatal(err)
}
}
deleted, err := s.Orders.SoftDeleteMissingForCookie(ctx, cid, map[string]struct{}{"seller-order": {}})
if err != nil || deleted != 1 {
t.Fatalf("deleted=%d err=%v", deleted, err)
}
if _, err := s.Orders.Get(ctx, "buyer-order"); !errors.Is(err, ErrNotFound) {
t.Fatalf("missing order should be hidden, err=%v", err)
}
if err := s.Orders.Upsert(ctx, "buyer-order", OrderUpsertOpts{CookieID: cid, OrderStatus: "pending_ship"}); err != nil {
t.Fatal(err)
}
if _, err := s.Orders.Get(ctx, "buyer-order"); err != nil {
t.Fatalf("reappeared order should be restored, err=%v", err)
}
}
// seedAccount 在临时库里建好 admin 用户 + 一个账号(cookie),返回 (userID, cookieID)。
// 多数订单/自动化/卡券测试都需要这两层外键先就位。
func seedAccount(t *testing.T, s *Store) (int64, string) {
+50 -2
View File
@@ -45,7 +45,7 @@ func (o *Orders) ListForUser(ctx context.Context, f OrderListFilter) ([]OrderRow
if f.Limit <= 0 {
f.Limit = 20
}
where := []string{"c.user_id=?"}
where := []string{"c.user_id=?", "o.deleted_at IS NULL"}
args := []any{f.UserID}
if f.CookieID != "" {
where = append(where, "o.cookie_id=?")
@@ -172,7 +172,7 @@ func (o *Orders) ByCookiePage(ctx context.Context, cookieID string, limit, offse
`SELECT order_id, item_id, buyer_id, spec_name, spec_value, quantity, amount,
order_status, is_bargain, system_shipped, receiver_name, receiver_phone,
receiver_address, receiver_city, created_at, updated_at
FROM orders WHERE cookie_id=? ORDER BY created_at DESC,order_id DESC LIMIT ? OFFSET ?`, cookieID, limit, offset)
FROM orders WHERE cookie_id=? AND deleted_at IS NULL ORDER BY created_at DESC,order_id DESC LIMIT ? OFFSET ?`, cookieID, limit, offset)
if err != nil {
return nil, err
}
@@ -205,6 +205,54 @@ func (o *Orders) ByCookiePage(ctx context.Context, cookieID string, limit, offse
return out, rows.Err()
}
// SoftDeleteMissingForCookie 将本次完整卖家订单同步中未出现的本地订单逻辑删除。
// activeIDs 为空表示线上已确认没有任何卖家订单;调用方必须确保同步完整成功后再调用。
func (o *Orders) SoftDeleteMissingForCookie(ctx context.Context, cookieID string, activeIDs map[string]struct{}) (int, error) {
if strings.TrimSpace(cookieID) == "" {
return 0, errors.New("cookie_id 不能为空")
}
rows, err := o.DB.QueryContext(ctx,
`SELECT order_id FROM orders WHERE cookie_id=? AND deleted_at IS NULL`, cookieID)
if err != nil {
return 0, err
}
orderIDs := make([]string, 0)
for rows.Next() {
var orderID string
if err := rows.Scan(&orderID); err != nil {
_ = rows.Close()
return 0, err
}
orderIDs = append(orderIDs, orderID)
}
if err := rows.Err(); err != nil {
_ = rows.Close()
return 0, err
}
if err := rows.Close(); err != nil {
return 0, err
}
deleted := 0
for _, orderID := range orderIDs {
if _, ok := activeIDs[orderID]; ok {
continue
}
result, err := o.DB.ExecContext(ctx, `UPDATE orders
SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND order_id=? AND deleted_at IS NULL`, cookieID, orderID)
if err != nil {
return deleted, err
}
changed, err := result.RowsAffected()
if err != nil {
return deleted, err
}
deleted += int(changed)
}
return deleted, nil
}
// OrderStatusMap 将数字状态码转换为文本状态。
var OrderStatusMap = map[string]string{
"paid": "pending_ship",
+6
View File
@@ -266,6 +266,12 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
// - contentType=26:交易卡片,如“我已拍下,待付款”“我发起了退款申请”
// 付款待发货卡片已经在 handleMessage 前半段进入 automation.Center,这里不能再进入聊天回复链。
func isNonUserChatNotice(m1, m10 map[string]any, reminder string) bool {
if strings.TrimSuffix(strings.TrimSpace(toString(m10["senderUserId"])), "@goofish") == "1400" {
return true
}
if strings.TrimSpace(reminder) == "发来一条新消息" {
return true
}
if sessionType := strings.TrimSpace(toString(m10["sessionType"])); sessionType != "" && sessionType != "1" {
return true
}
+9
View File
@@ -287,6 +287,15 @@ func TestIsNonUserChatNotice(t *testing.T) {
}
}
func TestIsNonUserChatNoticeFiltersOfficialSenderAndPlaceholder(t *testing.T) {
if !isNonUserChatNotice(map[string]any{}, map[string]any{"senderUserId": "1400", "reminderContent": "邀您填写售后问卷"}, "邀您填写售后问卷") {
t.Error("闲小蜜消息应判为官方系统消息")
}
if !isNonUserChatNotice(map[string]any{}, map[string]any{"senderUserId": "peer-1"}, "发来一条新消息") {
t.Error("官方通知占位文本不应进入聊天回复")
}
}
// TestToStringAndTrimFloatInt 数字/字符串安全转换。
func TestToStringAndTrimFloatInt(t *testing.T) {
if got := toString(float64(26)); got != "26" {
+1 -1
View File
@@ -120,7 +120,7 @@ func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) {
{`SELECT COUNT(*) FROM users`, &totalUsers},
{`SELECT COUNT(*) FROM cookies`, &totalCookies},
{`SELECT COUNT(*) FROM cards`, &totalCards},
{`SELECT COUNT(*) FROM orders`, &totalOrders},
{`SELECT COUNT(*) FROM orders WHERE deleted_at IS NULL`, &totalOrders},
{`SELECT COUNT(*) FROM keywords`, &totalKeywords},
}
for _, count := range counts {
+2 -2
View File
@@ -45,7 +45,7 @@ func (s *Server) dashboardStats(w http.ResponseWriter, r *http.Request) {
{"total_cards", `SELECT COUNT(*) FROM cards WHERE user_id=?`},
{"total_keywords", `SELECT COUNT(*) FROM keywords k WHERE EXISTS (
SELECT 1 FROM cookies c WHERE c.id=k.cookie_id AND c.user_id=?)`},
{"total_orders", `SELECT COUNT(*) FROM orders o WHERE EXISTS (
{"total_orders", `SELECT COUNT(*) FROM orders o WHERE o.deleted_at IS NULL AND EXISTS (
SELECT 1 FROM cookies c WHERE c.id=o.cookie_id AND c.user_id=?)`},
}
for _, item := range queries {
@@ -342,7 +342,7 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
// buildAnalyticsWhere 构建 WHERE 子句(user_id 经 cookies 关联过滤 + 日期 + 状态)。
// 返回 (whereClause, params),whereClause 已含 WHERE 前缀。
func buildAnalyticsWhere(startDate, endDate string, userID int64, statuses []string, location *time.Location) (string, []any) {
conds := []string{}
conds := []string{"orders.deleted_at IS NULL"}
params := []any{}
if startDate != "" {
conds = append(conds, "orders.created_at >= ?")
+10
View File
@@ -112,6 +112,10 @@ func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
if status != http.StatusOK || filtered["total"] != float64(1) || filtered["total_pages"] != float64(1) {
t.Fatalf("filtered status=%d body=%+v", status, filtered)
}
filteredCounts, ok := filtered["trigger_counts"].(map[string]any)
if !ok || filteredCounts[automation.TriggerOrderPaid] != float64(1) || len(filteredCounts) != 1 {
t.Fatalf("filtered trigger counts=%+v", filtered["trigger_counts"])
}
data, ok := filtered["data"].([]any)
if !ok || len(data) != 1 || data[0].(map[string]any)["name"] != "付款规则" {
t.Fatalf("filtered data=%+v", filtered["data"])
@@ -124,6 +128,12 @@ func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
if data, ok := lastPage["data"].([]any); !ok || len(data) != 1 {
t.Fatalf("last page data=%+v", lastPage["data"])
}
lastPageCounts, ok := lastPage["trigger_counts"].(map[string]any)
if !ok || lastPageCounts[automation.TriggerOrderPaid] != float64(1) ||
lastPageCounts[automation.TriggerBuyerReviewed] != float64(1) ||
lastPageCounts[automation.TriggerReviewMissingTimeout] != float64(1) {
t.Fatalf("last page trigger counts=%+v", lastPage["trigger_counts"])
}
status, _ = request("/automation-rules?page=1&enabled=maybe")
if status != http.StatusBadRequest {
+10 -1
View File
@@ -161,6 +161,15 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
filter := db.AutomationRuleListFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"),
}
triggerCounts, err := s.Store.Automation.CountByTriggerForUser(r.Context(), filter)
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计自动化规则失败")
return
}
totalPages := (total + pageSize - 1) / pageSize
if totalPages > 0 && page > totalPages {
page = totalPages
@@ -175,7 +184,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true, "data": automationRulesJSON(rules), "total": total,
"page": page, "page_size": pageSize, "total_pages": totalPages,
"page": page, "page_size": pageSize, "total_pages": totalPages, "trigger_counts": triggerCounts,
})
}
+7
View File
@@ -94,6 +94,13 @@ func TestOrderListAndDetail(t *testing.T) {
if rec3.Code != 200 {
t.Fatalf("delete status=%d", rec3.Code)
}
var deletedAt string
if err := store.DB.QueryRowContext(ctx, `SELECT COALESCE(deleted_at,'') FROM orders WHERE order_id=?`, "ord1").Scan(&deletedAt); err != nil || deletedAt == "" {
t.Fatalf("订单删除应为逻辑删除,deleted_at=%q err=%v", deletedAt, err)
}
if _, err := store.Orders.Get(ctx, "ord1"); err == nil {
t.Fatal("逻辑删除订单不应再出现在活动订单查询中")
}
}
// TestCardCRUD 卡券增删改查。
+34 -6
View File
@@ -408,13 +408,21 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
if runtimeCookieChanged {
s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie)
}
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
syncResult, syncErr := s.syncSyncedItems(r.Context(), req.CookieID, res.Items)
if syncErr != nil {
if s.Logger != nil {
s.Logger.Error("同步商品到本地失败", "cookie_id", req.CookieID, "err", syncErr)
}
writeErr(w, http.StatusInternalServerError, "保存商品同步结果失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(saved) + " 件",
"total_count": len(res.Items),
"total_pages": res.TotalPages,
"saved_count": saved,
"success": true,
"message": "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(syncResult.Saved) + " 件,删除 " + strconv.Itoa(syncResult.Deleted) + " 件",
"total_count": len(res.Items),
"total_pages": res.TotalPages,
"saved_count": syncResult.Saved,
"deleted_count": syncResult.Deleted,
})
}
@@ -554,6 +562,26 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
return saved
}
func (s *Server) syncSyncedItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) (db.ItemSyncResult, error) {
rows := make([]db.ItemInfoRow, 0, len(items))
for _, item := range items {
priceText := item.PriceText
if priceText == "" {
priceText = item.Price
}
rows = append(rows, db.ItemInfoRow{
CookieID: cookieID,
ItemID: item.ID,
ItemTitle: item.Title,
ItemCategory: item.CategoryID,
ItemPrice: priceText,
ItemDetail: item.ItemDetail,
IsMultiSpec: item.IsMultiSpec,
})
}
return s.Store.Items.SyncFromRemote(ctx, cookieID, rows)
}
func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) {
fetcher, ok := client.(mtop.ItemDetailFetcher)
if !ok {
+27 -9
View File
@@ -13,6 +13,7 @@ import (
"testing"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
@@ -373,6 +374,21 @@ func TestPublishItemStockPermissionMissing(t *testing.T) {
func TestSyncItemsFromAccountSuccess(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: "acc1", ItemID: "it-sync-1", ItemTitle: "旧标题", ItemDescription: "本地描述", ItemPrice: "¥9.90",
}); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiSpec(ctx, "acc1", "it-sync-1", true); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiQuantity(ctx, "acc1", "it-sync-1", true); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: "acc1", ItemID: "it-removed", ItemTitle: "已删除商品"}); err != nil {
t.Fatal(err)
}
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
body := `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[` +
@@ -402,16 +418,18 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
if res["saved_count"] != float64(1) {
t.Fatalf("应保存1件商品: %+v", res)
}
// 验证 DB 已写入。
items, _ := store.Items.AllForCookie(context.Background(), "acc1")
found := false
for _, it := range items {
if it.ItemID == "it-sync-1" && it.ItemTitle == "同步商品A" {
found = true
}
if res["deleted_count"] != float64(1) {
t.Fatalf("应删除1件已下架商品: %+v", res)
}
if !found {
t.Fatalf("商品未保存: %+v", items)
// 验证 DB 已写入。
items, _ := store.Items.AllForCookie(ctx, "acc1")
if len(items) != 1 {
t.Fatalf("同步后本地应只保留1件商品: %+v", items)
}
item := items[0]
if item.ItemID != "it-sync-1" || item.ItemTitle != "同步商品A" || item.ItemPrice != "¥12.50" || item.ItemDescription != "本地描述" ||
!item.IsMultiSpec || !item.MultiQuantityDelivery {
t.Fatalf("线上商品更新或本地配置保留异常: %+v", item)
}
}
@@ -1099,7 +1099,7 @@ func (s *Server) ensurePublishAutomationRule(ctx context.Context, input db.Autom
var exists bool
err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS(
SELECT 1 FROM automation_rules
WHERE user_id=? AND cookie_id=? AND item_id=? AND trigger_type=? AND name=?
WHERE user_id=? AND cookie_id=? AND item_id=? AND trigger_type=? AND name=? AND deleted_at IS NULL
)`, input.UserID, input.CookieID, input.ItemID, input.TriggerType, input.Name).Scan(&exists)
if err != nil {
return err
+25 -19
View File
@@ -187,7 +187,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
all = map[string]string{cookieID: value}
}
discovered, listUpdated, failed := 0, 0, 0
discovered, listUpdated, softDeleted, failed := 0, 0, 0, 0
results := []map[string]any{}
newOrderIDs := make(map[string]struct{})
if fetcher, ok := s.mtopClient().(mtop.SoldOrderFetcher); ok {
@@ -207,7 +207,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
}
all[cid] = latest.Value
mtopCtx, cookieSession := withMTopCookieSnapshot(r.Context(), latest)
accountDiscovered, accountUpdated, accountNewIDs, discoveryErr := s.discoverSoldOrders(mtopCtx, fetcher, cid, latest.Value)
accountDiscovered, accountUpdated, accountNewIDs, accountRemoteIDs, discoveryErr := s.discoverSoldOrders(mtopCtx, fetcher, cid, latest.Value)
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
discoveryErr = errors.Join(discoveryErr, fmt.Errorf("保存订单列表响应 Cookie Jar: %w", persistErr))
@@ -227,6 +227,16 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
"cookie_id": cid, "stage": "discover", "success": discoveryErr == nil,
"discovered": accountDiscovered, "updated": accountUpdated,
}
if discoveryErr == nil {
deleted, deleteErr := s.Store.Orders.SoftDeleteMissingForCookie(r.Context(), cid, accountRemoteIDs)
if deleteErr != nil {
discoveryErr = fmt.Errorf("标记缺失订单失败: %w", deleteErr)
result["success"] = false
} else {
softDeleted += deleted
result["soft_deleted"] = deleted
}
}
if discoveryErr != nil {
failed++
result["error"] = discoveryErr.Error()
@@ -280,7 +290,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
"success": failed == 0,
"message": message,
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "detail_total": total,
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
"total": total, "updated": 0, "no_change": 0, "failed": failed,
},
"results": results,
@@ -292,7 +302,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
"success": failed == 0,
"message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "detail_total": 0,
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": 0,
"total": 0, "updated": 0, "no_change": 0, "failed": failed,
},
"results": results,
@@ -373,30 +383,31 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
"success": failed == 0,
"message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "detail_total": total,
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
"total": total, "updated": updated, "no_change": noChange, "failed": failed,
},
"results": results,
})
}
func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, error) {
func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, map[string]struct{}, error) {
discovered, updated := 0, 0
newOrderIDs := make(map[string]struct{})
remoteOrderIDs := make(map[string]struct{})
for pageNumber := 1; pageNumber <= maxSoldOrderPages; pageNumber++ {
page, err := fetcher.FetchSoldOrdersPage(ctx, cookies, pageNumber, 30)
if err != nil {
return discovered, updated, newOrderIDs, err
return discovered, updated, newOrderIDs, remoteOrderIDs, err
}
pageChanged := false
for _, remote := range page.Items {
remoteOrderIDs[remote.OrderID] = struct{}{}
if normalizedAmount, ok := db.NormalizeOrderAmount(remote.Amount); ok {
remote.Amount = normalizedAmount
}
existing, getErr := s.Store.Orders.Get(ctx, remote.OrderID)
isNew := errors.Is(getErr, db.ErrNotFound)
if getErr != nil && !isNew {
return discovered, updated, newOrderIDs, fmt.Errorf("读取订单 %s 失败: %w", remote.OrderID, getErr)
return discovered, updated, newOrderIDs, remoteOrderIDs, fmt.Errorf("读取订单 %s 失败: %w", remote.OrderID, getErr)
}
changed := isNew || soldOrderChanged(existing, remote)
status := remote.OrderStatus
@@ -415,7 +426,7 @@ func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderF
ReceiverAddr: remote.ReceiverAddr, ReceiverCity: remote.ReceiverCity,
IsBargain: isBargain,
}); err != nil {
return discovered, updated, newOrderIDs, fmt.Errorf("保存订单 %s 失败: %w", remote.OrderID, err)
return discovered, updated, newOrderIDs, remoteOrderIDs, fmt.Errorf("保存订单 %s 失败: %w", remote.OrderID, err)
}
if isNew {
discovered++
@@ -423,17 +434,12 @@ func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderF
} else if changed {
updated++
}
pageChanged = pageChanged || changed
}
if !page.NextPage || len(page.Items) == 0 {
return discovered, updated, newOrderIDs, nil
}
// 卖家列表按新到旧排列。一整页都已存在且字段未变化时,更早页也无需重复扫描。
if !pageChanged {
return discovered, updated, newOrderIDs, nil
return discovered, updated, newOrderIDs, remoteOrderIDs, nil
}
}
return discovered, updated, newOrderIDs, fmt.Errorf("订单列表超过 %d 页,已停止继续同步", maxSoldOrderPages)
return discovered, updated, newOrderIDs, remoteOrderIDs, fmt.Errorf("订单列表超过 %d 页,已停止继续同步", maxSoldOrderPages)
}
func soldOrderChanged(existing *db.Order, remote mtop.SoldOrder) bool {
@@ -559,13 +565,13 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "订单刷新完成", "order": detail})
}
// deleteOrder 删除订单。
// deleteOrder 逻辑删除订单,保留订单历史,避免破坏自动化审计数据。
func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
orderID := chi.URLParam(r, "order_id")
if _, ok := s.requireOrderOwner(w, r, orderID); !ok {
return
}
_, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM orders WHERE order_id=?`, orderID)
_, err := s.Store.Orders.SoftDelete(r.Context(), orderID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
@@ -61,6 +61,39 @@ func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
}
}
func TestRefreshOrdersSoftDeletesOrdersMissingFromSellerList(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,buyer_id,cookie_id,order_status) VALUES ('buyer-order','buy-item','seller-account','acc1','pending_ship')`)
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"1"},"priceInfo":{"amount":{"value":"10.00"}}}}]}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}
body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` +
`"commonData":{"orderId":"seller-order","itemId":"seller-item","orderStatus":"待发货"},` +
`"buyerInfoVO":{"buyerId":"buyer-1"},"priceVO":{"totalPrice":"10.00","buyNum":"1"}}]}}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"soft_deleted":1`) {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var deletedAt string
if err := store.DB.QueryRowContext(ctx, `SELECT COALESCE(deleted_at,'') FROM orders WHERE order_id=?`, "buyer-order").Scan(&deletedAt); err != nil || deletedAt == "" {
t.Fatalf("缺失订单应逻辑删除,deleted_at=%q err=%v", deletedAt, err)
}
if _, err := store.Orders.Get(ctx, "buyer-order"); err == nil {
t.Fatal("逻辑删除的购买订单不应再出现在活动订单查询中")
}
}
func TestMissingRefreshResultsAreCounted(t *testing.T) {
targets := []refreshTarget{{OrderID: "a"}, {OrderID: "b"}, {OrderID: "c"}}
missing := missingRefreshTargetIDs(targets, map[string]struct{}{"b": {}})
@@ -0,0 +1 @@
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media(min-width:640px){.\!container{max-width:640px!important}.container{max-width:6Line truncated
@@ -1,19 +0,0 @@
import{j as e,r,b as Fe,c as aa,d as Ra}from"./react-vendor-C_od1ZSF.js";import{L as $a,U as la,M as ts,C as ss,B as ra,S as na,Z as as,a as yt,b as us,c as hs,d as gs,e as Pa,f as rt,A as ks,D as Da,g as Cs,P as ia,h as At,E as oa,T as Ea,i as Ta,j as Re,X as $e,k as Fa,l as Ma,m as bs,n as ca,o as He,Q as Qt,p as ot,q as Ke,r as ft,s as It,t as Ss,R as Be,u as da,v as qa,w as Qe,K as Ba,x as it,y as lt,z as tt,F as Ls,G as _t,H as jt,I as Ot,J as xa,N as za,O as Os,V as Is,W as Ua,Y as Wa,_ as Va,$ as Ja,a0 as Gt,a1 as Dt,a2 as ls,a3 as Qa,a4 as Ga,a5 as rs,a6 as Ka,a7 as Ha,a8 as ns,a9 as As,aa as zt,ab as ma,ac as Za,ad as Ya,ae as Wt,af as pa,ag as Xa,ah as el,ai as tl,aj as sl,ak as al,al as ll,am as rl}from"./icons-vendor-DjsKcZkz.js";import{R as Et,B as nl,X as Rs,Y as $s,T as Tt,a as il,C as Kt,A as ol,b as cl,c as dl,P as Ps,d as Ds,L as xl}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const x of document.querySelectorAll('link[rel="modulepreload"]'))i(x);new MutationObserver(x=>{for(const v of x)if(v.type==="childList")for(const S of v.addedNodes)S.tagName==="LINK"&&S.rel==="modulepreload"&&i(S)}).observe(document,{childList:!0,subtree:!0});function l(x){const v={};return x.integrity&&(v.integrity=x.integrity),x.referrerPolicy&&(v.referrerPolicy=x.referrerPolicy),x.crossOrigin==="use-credentials"?v.credentials="include":x.crossOrigin==="anonymous"?v.credentials="omit":v.credentials="same-origin",v}function i(x){if(x.ep)return;x.ep=!0;const v=l(x);fetch(x.href,v)}})();const ml=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),is=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.8Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(us,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Pt,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:R,children:"取消"}),e.jsxs("button",{onClick:Je,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:R,children:[R?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),R?"保存中...":"保存"]})]})})]})}),document.body)]})},Qr=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(s=>({order_id:String((s==null?void 0:s.order_id)||"unknown"),success:(s==null?void 0:s.success)===!0,message:String((s==null?void 0:s.message)||"")})):[]}),Gr=t=>(t==null?void 0:t.results.filter(s=>!s.success))||[],Qs=({status:t})=>{const s={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:l[t]||t})},Kr=()=>{const[t,s]=r.useState([]),[l,i]=r.useState([]),[x,v]=r.useState([]),[S,$]=r.useState({}),[f,I]=r.useState("all"),[y,J]=r.useState(""),[H,me]=r.useState(""),[ne,N]=r.useState(""),M=r.useRef(0),[ie,G]=r.useState(1),[Z,W]=r.useState(1),[ge,ue]=r.useState(!1),[O,Q]=r.useState(!1),[ce,q]=r.useState(!1),[V,A]=r.useState(!1),[D,ae]=r.useState(null),[E,le]=r.useState(null),[Se,je]=r.useState({}),[pe,u]=r.useState(!1),[b,z]=r.useState(""),[w,Y]=r.useState(!1),[oe,he]=r.useState(null),[Ie,fe]=r.useState(null),[d,k]=r.useState(null),[p,c]=r.useState(!1),[_,R]=r.useState(null),[U,K]=r.useState(null),te=async()=>{const g=++M.current;ue(!0);try{const B=await zl(y||void 0,f,ie,20,ne);if(g!==M.current)return;s(B.data),W(B.total_pages)}catch(B){console.error("加载订单失败:",B)}finally{g===M.current&&ue(!1)}},Ne=(g,B,_e)=>{if(_e&&_e.trim())return _e;if(S[`${g}:${B}`])return S[`${g}:${B}`];const Oe=l.find(Ye=>{if(_e&&Ye.item_title){const st=_e.toLowerCase(),Xe=Ye.item_title.toLowerCase();return Xe.includes(st)||st.includes(Xe)}return!1});return Oe!=null&&Oe.item_title?Oe.item_title:"未知商品"},h=g=>{const B={};g.forEach(_e=>{_e.item_id&&(B[`${_e.cookie_id}:${_e.item_id}`]=_e.item_title||_e.item_id)}),$(B)};r.useEffect(()=>{const g=window.setTimeout(()=>{G(1),N(H.trim())},300);return()=>window.clearTimeout(g)},[H]),r.useEffect(()=>{te()},[y,f,ie,ne]),r.useEffect(()=>{Promise.all([Rt(),Nt()]).then(([g,B])=>{v(g),i(B),h(B)}).catch(g=>{console.error("加载商品列表失败:",g)})},[]);const C=r.useMemo(()=>new Map(x.map(g=>[g.id,g])),[x]),F=g=>{const B=C.get(g),_e=(B==null?void 0:B.remark)||(B==null?void 0:B.nickname);return _e?`${_e} · ${g.slice(0,6)}`:`账号 ${g.slice(0,8)}`},T=g=>{const B=C.get(g);return(B==null?void 0:B.remark)||(B==null?void 0:B.nickname)||"未命名账号"},ve=async()=>{ue(!0);try{const g=await Vl(y||void 0,f);await te(),g!=null&&g.message&&alert(g.message)}catch(g){console.error("同步订单失败:",g),alert((g==null?void 0:g.message)||"同步失败,请重试")}finally{ue(!1)}},Ee=g=>{z(g),he(null),u(!0)},we=async g=>{var B;Y(!0),he(null);try{const _e=await Ql([b],g),Oe=(B=_e==null?void 0:_e.results)==null?void 0:B[0];Oe!=null&&Oe.success?(he({success:!0,message:Oe.message}),te()):he({success:!1,message:(Oe==null?void 0:Oe.message)||"发货失败"})}catch(_e){he({success:!1,message:(_e==null?void 0:_e.message)||"请求失败"})}finally{Y(!1)}},Pe=g=>{ae(g),Q(!0)},de=g=>{le({...g}),q(!0)},Te=async()=>{if(!(!E||!E.order_id))try{const g={};E.status!==void 0&&(g.order_status=E.status),E.buyer_id!==void 0&&(g.buyer_id=E.buyer_id),E.amount!==void 0&&(g.amount=E.amount),E.receiver_name!==void 0&&(g.receiver_name=E.receiver_name),E.receiver_phon Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(U=>U.map(K=>`"${String(K).replace(/"/g,'""')}"`).join(",")).join(`
`),c=new Blob(["\uFEFF"+p],{type:"text/csv;charset=utf-8"}),_=URL.createObjectURL(c),R=document.createElement("a");R.href=_,R.download="卡密组批量导入模板.csv",document.body.appendChild(R),R.click(),R.remove(),URL.revokeObjectURL(_)},he=async()=>{if(M){ge(!0),Z(null);try{const d=await er(M);if(Z(d),d.created>0){const k=await et();s(k)}}catch(d){Z({error:(d==null?void 0:d.message)||"上传失败"})}finally{ge(!1)}}},Ie=async()=>{if(!(!ue||!Q.trim())){ge(!0),V(null);try{const d=await tr(ue,Q);V({added:d.added}),ce("");const k=await et();s(k)}catch(d){alert("追加失败:"+((d==null?void 0:d.message)||"未知错误"))}finally{ge(!1)}}},fe=()=>{var d;N("create"),ie(null),Z(null),O((d=w[0])!=null&&d.id?String(w[0].id):""),ce(""),V(null),me(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:fe,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Ot,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>v(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(tt,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(xa,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:A,onChange:d=>D(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(_t,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:ae,onChange:d=>E(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",Y.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:Y.map(d=>{let k="";return d.type==="data"&&d.data_content?k=`库存: ${d.data_content.split(`
`).filter(c=>c.trim()).length} 条`:d.type==="text"&&d.text_content?k=d.text_content:d.type==="api"&&d.api_config?k=d.api_config.url:d.type==="image"&&d.image_url&&(k="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(le,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>z(d.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(za,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:k,children:k})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(d),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Se(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(jt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>pe(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Qe,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),Y.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ia,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&S&&Fe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx($e,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:f.name||"",onChange:d=>I({...f,name:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:f.type||"text",onChange:d=>I({...f,type:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(S==null?void 0:S.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),f.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:f.api_url||"",onChange:d=>I({...f,api_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:f.data_content?f.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),f.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:f.image_url||"",onChange:d=>I({...f,image_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),f.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:f.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:f.delay_seconds||0,onChange:d=>I({...f,delay_seconds:parseInt(d.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:f.description||"",onChange:d=>I({...f,description:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>I({...f,enabled:!f.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${f.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${f.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:je,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),x&&Fe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>v(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx($e,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:y.name,onChange:d=>J({...y,name:d.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(ss,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-grayLine truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),y.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:y.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),y.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:y.api_method,onChange:d=>J({...y,api_method:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:y.api_timeout,onChange:d=>J({...y,api_timeout:parseInt(d.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:y.api_headers,onChange:d=>J({...y,api_headers:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:y.api_params,onChange:d=>J({...y,api_params:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:y.description,onChange:d=>J({...y,description:d.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:y.delay_seconds,onChange:d=>J({...y,delay_seconds:parseInt(d.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:u,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),H&&Fe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx($e,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>N("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 ${ne==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ua,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>N("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 ${ne==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ot,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),ne==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:oe,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),q&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",q.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),ne==="create"?e.jsxs("button",{onClick:he,disabled:!M||W,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[W?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(Ot,{className:"w-4 h-4"}),W?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ie,disabled:!ue||!Q.trim()||W||w.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[W?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(tt,{className:"w-4 h-4"}),W?"处理中...":"追加卡密"]})]})]})}),document.body)]})},Yr=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Xr=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},en=({onConfigureDelivery:t})=>{const[s,l]=r.useState([]),[i,x]=r.useState([]),[v,S]=r.useState([]),[$,f]=r.useState(""),[I,y]=r.useState(""),[J,H]=r.useState(!1),[me,ne]=r.useState(!1),[N,M]=r.useState(!1),[ie,G]=r.useState(!1),[Z,W]=r.useState(!1),[ge,ue]=r.useState(!1),[O,Q]=r.useState(!1),[ce,q]=r.useState("upload"),[V,A]=r.useState(null),[D,ae]=r.useState(null),[E,le]=r.useState(""),[Se,je]=r.useState(!1),[pe,u]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[b,z]=r.useState(null),[w,Y]=r.useState(null),[oe,he]=r.useState(null),Ie=r.useRef(!1),[fe,d]=r.useState(null),[k,p]=r.useState({}),[c,_]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[R,U]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[K,te]=r.useState([]);r.useEffect(()=>{if(!ge||R.images.length===0){te([]);return}const n=R.images.map((L,re)=>({key:L.name+re,url:URL.createObjectURL(L)}));return te(n),()=>{n.forEach(L=>URL.revokeObjectURL(L.url))}},[ge,R.images]);const Ne=async()=>{const n=await Nt();l(n)},h=async()=>{x(await xs())};r.useEffect(()=>{Promise.all([Rt(),Nt(),xs(),Bs(20)]).then(([n,L,re,Ve])=>{S(n),l(L),x(re);const Je=Ve.find(qe=>["running","canceling"].includes(qe.status))||Ve.find(qe=>qe.status!=="preview");he(Je||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!O||!(w!=null&&w.id)||!["running","canceling"].includes(w.status))return;const n=window.setInterval(async()=>{if(!Ie.current){Ie.current=!0;try{const L=await gt(w.id);Y(L),he(L),["running","canceling"].includes(L.status)||(q("done"),await Ne(),await h())}catch(L){console.error("刷新批量铺货进度失败:",L)}finally{Ie.current=!1}}},3e3);return()=>{window.clearInterval(n)}},[O,w==null?void 0:w.id,w==null?void 0:w.status]);const C=async()=>{if(!$)return alert("请先选择账号");H(!0);try{const n=await sr($);await Ne(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{H(!1)}},F=n=>{d(n),p({...n}),G(!0)},T=async()=>{if(fe)try{await mr(fe.cookie_id,fe.item_id,{item_title:k.item_title||"",item_description:k.item_description||"",item_category:k.item_category||"",item_price:k.item_price||"",item_detail:k.item_detail||fe.item_detail||""}),await Ne(),await h(),G(!1),d(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},ve=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await ar(n.cookie_id,n.item_id),l(L=>L.filter(re=>!(re.cookie_id===n.cookie_id&&re.item_id===n.item_id)))}catch(L){console.error("删除商品失败:",L),alert("删除失败,请重试")}},Ee=async()=>{try{if(!c.cookie_id||!c.item_id){alert("请选择账号并填写商品ID");return}await lr(c.cookie_id,{item_id:c.item_id,item_title:c.item_title,item_price:c.item_price,item_detail:c.item_image?JSON.stringify({item_image:c.item_image}):""}),await Ne(),W(!1),_({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},we=async()=>{if(!R.cookie_id)return alert("请选择发布账号");if(!R.title.trim())return alert("请填写商品标题");if(!R.price.trim())return alert("请填写商品价格");if(!R.quantity||Number(R.quantity)<=0)return alert("库存数量必须大于 0");if(R.images.length===0)return alert("至少上传 1 张商品图片");if(R.postage_mode==="fixe Line truncated
`),Ve=new Blob(["\uFEFF"+re],{type:"text/csv;charset=utf-8"}),Je=URL.createObjectURL(Ve),qe=document.createElement("a");qe.href=Je,qe.download="批量铺货模板.csv",document.body.appendChild(qe),qe.click(),qe.remove(),URL.revokeObjectURL(Je)},Oe=()=>{_(n=>({...n,cookie_id:$||n.cookie_id})),W(!0)},Ye=()=>{U(n=>({...n,cookie_id:$||n.cookie_id})),ue(!0)},st=n=>i.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id).length>0?i.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id):i.filter(L=>L.cookie_id===n.cookie_id&&!L.item_id),Xe=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ze=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},We=r.useMemo(()=>new Map(v.map(n=>[n.id,n])),[v]),ct=r.useMemo(()=>I?s.filter(n=>n.cookie_id===I):s,[I,s]),Ge=n=>{const L=We.get(n),re=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return re?`${re} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},dt=n=>{const L=We.get(n);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ja,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:n=>y(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),v.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ot,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:$,onChange:n=>f(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),v.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:C,disabled:J||!$,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Be,{className:`w-4 h-4 ${J?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Oe,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(tt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ye,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Gt,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Pe(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Dt,{className:"w-4 h-4"}),oe&&["running","canceling"].includes(oe.status)?"继续批量任务":"批量铺货"]}),oe&&!["running","canceling"].includes(oe.status)&&e.jsx("button",{onClick:()=>void Te(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[ct.map(n=>{const L=st(n),re=L.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group r Line truncated
@@ -0,0 +1,19 @@
import{j as e,r,b as qe,c as na,d as Da}from"./react-vendor-C_od1ZSF.js";import{L as Ta,U as ia,M as ss,C as as,B as oa,S as ca,Z as ls,a as ft,b as hs,c as gs,d as bs,e as Ea,f as nt,A as Cs,D as Ma,g as Ss,P as da,h as Rt,E as xa,T as qa,i as Fa,j as Pe,X as De,k as Ba,l as za,m as ys,n as ma,o as Ye,Q as Gt,p as mt,q as Ze,r as yt,s as At,t as Ls,R as Ue,u as pa,v as Ua,w as Ke,K as Wa,x as xt,y as rt,z as at,F as Os,G as _t,H as jt,I as It,J as ua,N as Va,O as Is,V as As,W as Ja,Y as Qa,_ as Ga,$ as Ka,a0 as Kt,a1 as Tt,a2 as rs,a3 as Ha,a4 as Za,a5 as ns,a6 as Ya,a7 as Xa,a8 as is,a9 as Rs,aa as Ut,ab as ha,ac as el,ad as tl,ae as Vt,af as ga,ag as sl,ah as al,ai as ll,aj as rl,ak as nl,al as il,am as ol}from"./icons-vendor-DjsKcZkz.js";import{R as Et,B as cl,X as $s,Y as Ps,T as Mt,a as dl,C as Ht,A as xl,b as ml,c as pl,P as Ds,d as Ts,L as ul}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const v of m)if(v.type==="childList")for(const k of v.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&i(k)}).observe(document,{childList:!0,subtree:!0});function l(m){const v={};return m.integrity&&(v.integrity=m.integrity),m.referrerPolicy&&(v.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?v.credentials="include":m.crossOrigin==="anonymous"?v.credentials="omit":v.credentials="same-origin",v}function i(m){if(m.ep)return;m.ep=!0;const v=l(m);fetch(m.href,v)}})();const hl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),os=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Dt,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:I,children:"取消"}),e.jsxs("button",{onClick:Ge,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:I,children:[I?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),I?"保存中...":"保存"]})]})})]})}),document.body)]})},Hr=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(s=>({order_id:String((s==null?void 0:s.order_id)||"unknown"),success:(s==null?void 0:s.success)===!0,message:String((s==null?void 0:s.message)||"")})):[]}),Zr=t=>(t==null?void 0:t.results.filter(s=>!s.success))||[],Gs=({status:t})=>{const s={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:l[t]||t})},Yr=()=>{const[t,s]=r.useState([]),[l,i]=r.useState([]),[m,v]=r.useState([]),[k,D]=r.useState({}),[g,R]=r.useState("all"),[f,Q]=r.useState(""),[Z,me]=r.useState(""),[ce,_]=r.useState(""),q=r.useRef(0),[de,G]=r.useState(1),[Y,U]=r.useState(1),[fe,ge]=r.useState(!1),[O,K]=r.useState(!1),[xe,F]=r.useState(!1),[J,$]=r.useState(!1),[E,se]=r.useState(null),[M,ae]=r.useState(null),[Le,Ne]=r.useState({}),[pe,u]=r.useState(!1),[h,W]=r.useState(""),[w,X]=r.useState(!1),[ne,_e]=r.useState(null),[Re,be]=r.useState(null),[c,N]=r.useState(null),[le,d]=r.useState(!1),[p,I]=r.useState(null),[A,H]=r.useState(null),P=async()=>{const x=++q.current;ge(!0);try{const T=await Vl(f||void 0,g,de,20,ce);if(x!==q.current)return;s(T.data),U(T.total_pages)}catch(T){console.error("加载订单失败:",T)}finally{x===q.current&&ge(!1)}},we=(x,T,ie)=>{if(ie&&ie.trim())return ie;if(k[`${x}:${T}`])return k[`${x}:${T}`];const re=l.find(We=>{if(ie&&We.item_title){const et=ie.toLowerCase(),tt=We.item_title.toLowerCase();return tt.includes(et)||et.includes(tt)}return!1});return re!=null&&re.item_title?re.item_title:"未知商品"},Oe=x=>{const T={};x.forEach(ie=>{ie.item_id&&(T[`${ie.cookie_id}:${ie.item_id}`]=ie.item_title||ie.item_id)}),D(T)};r.useEffect(()=>{const x=window.setTimeout(()=>{G(1),_(Z.trim())},300);return()=>window.clearTimeout(x)},[Z]),r.useEffect(()=>{P()},[f,g,de,ce]),r.useEffect(()=>{Promise.all([$t(),Nt()]).then(([x,T])=>{v(x),i(T),Oe(T)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const $e=r.useMemo(()=>new Map(m.map(x=>[x.id,x])),[m]),Te=x=>{const T=$e.get(x),ie=(T==null?void 0:T.remark)||(T==null?void 0:T.nickname);return ie?`${ie} · ${x.slice(0,6)}`:`账号 ${x.slice(0,8)}`},Ee=x=>{const T=$e.get(x);return(T==null?void 0:T.remark)||(T==null?void 0:T.nickname)||"未命名账号"},y=async()=>{ge(!0);try{const x=await Gl(f||void 0,g);await P(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{ge(!1)}},C=x=>{W(x),_e(null),u(!0)},B=async x=>{var T;X(!0),_e(null);try{const ie=await Hl([h],x),re=(T=ie==null?void 0:ie.results)==null?void 0:T[0];re!=null&&re.success?(_e({success:!0,message:re.message}),P()):_e({success:!1,message:(re==null?void 0:re.message)||"发货失败"})}catch(ie){_e({success:!1,message:(ie==null?void 0:ie.message)||"请求失败"})}finally{X(!1)}},V=x=>{se(x),K(!0)},ke=x=>{ae({...x}),F(!0)},Me=async()=>{if(!(!M||!M.order_id))try{const x={};M.status!==void 0&&(x.order_status=M.status),M.buyer_id!==void 0&&(x.buyer_id=M.buyer_id),M.amount!==void 0&&(x.amount=M.amount),M.receiver_name!==void 0&&(x.receiver_name=M.receiver_name),M.receiver_phone!== Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(A=>A.map(H=>`"${String(H).replace(/"/g,'""')}"`).join(",")).join(`
`),d=new Blob(["\uFEFF"+le],{type:"text/csv;charset=utf-8"}),p=URL.createObjectURL(d),I=document.createElement("a");I.href=p,I.download="卡密组批量导入模板.csv",document.body.appendChild(I),I.click(),I.remove(),URL.revokeObjectURL(p)},_e=async()=>{if(q){fe(!0),Y(null);try{const c=await ar(q);if(Y(c),c.created>0){const N=await st();s(N)}}catch(c){Y({error:(c==null?void 0:c.message)||"上传失败"})}finally{fe(!1)}}},Re=async()=>{if(!(!ge||!K.trim())){fe(!0),J(null);try{const c=await lr(ge,K);J({added:c.added}),xe("");const N=await st();s(N)}catch(c){alert("追加失败:"+((c==null?void 0:c.message)||"未知错误"))}finally{fe(!1)}}},be=()=>{var c;_("create"),de(null),Y(null),O((c=w[0])!=null&&c.id?String(w[0].id):""),xe(""),J(null),me(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:be,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(It,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>v(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(at,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ua,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:$,onChange:c=>E(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(_t,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:se,onChange:c=>M(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",X.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:X.map(c=>{let N="";return c.type==="data"&&c.data_content?N=`库存: ${c.data_content.split(`
`).filter(d=>d.trim()).length} 条`:c.type==="text"&&c.text_content?N=c.text_content:c.type==="api"&&c.api_config?N=c.api_config.url:c.type==="image"&&c.image_url&&(N="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ae,{type:c.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:c.name,children:c.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>W(c.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:c.id}),e.jsx(Va,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${c.type==="text"?"bg-blue-50 text-blue-600":c.type==="data"?"bg-purple-50 text-purple-600":c.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:c.type==="text"?"文本":c.type==="data"?"批量":c.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:N,children:N})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:c.description||"-",children:c.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>h(c),className:`w-12 h-8 rounded-full relative transition-colors ${c.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${c.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Le(c),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(jt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>pe(c.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ke,{className:"h-4 w-4"})})]})})]},c.id)})})]})}),X.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(da,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&k&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(De,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:c=>R({...g,name:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:c=>R({...g,type:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(k==null?void 0:k.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:c=>R({...g,api_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
`).filter(c=>c.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:c=>R({...g,image_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:c=>{c.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:c=>R({...g,delay_seconds:parseInt(c.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:c=>R({...g,description:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>R({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ne,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ye,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),m&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>v(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(De,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:f.name,onChange:c=>Q({...f,name:c.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(as,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Is,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),f.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:f.content.split(`
`).filter(c=>c.trim()).length})," 条"]})]}),f.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:f.api_method,onChange:c=>Q({...f,api_method:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:f.api_timeout,onChange:c=>Q({...f,api_timeout:parseInt(c.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:f.api_headers,onChange:c=>Q({...f,api_headers:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:f.api_params,onChange:c=>Q({...f,api_params:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:f.description,onChange:c=>Q({...f,description:c.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:f.delay_seconds,onChange:c=>Q({...f,delay_seconds:parseInt(c.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:u,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(at,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Z&&qe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(De,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>_("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 ${ce==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ja,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>_("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 ${ce==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(It,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),ce==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:ne,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 tran Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),F&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",F.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),ce==="create"?e.jsxs("button",{onClick:_e,disabled:!q||U,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(It,{className:"w-4 h-4"}),U?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Re,disabled:!ge||!K.trim()||U||w.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(at,{className:"w-4 h-4"}),U?"处理中...":"追加卡密"]})]})]})}),document.body)]})},tn=t=>t.find(s=>s.status==="running"||s.status==="canceling"),sn=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},an=({onConfigureDelivery:t})=>{const[s,l]=r.useState([]),[i,m]=r.useState([]),[v,k]=r.useState([]),[D,g]=r.useState(""),[R,f]=r.useState(""),[Q,Z]=r.useState(!1),[me,ce]=r.useState(!1),[_,q]=r.useState(!1),[de,G]=r.useState(!1),[Y,U]=r.useState(!1),[fe,ge]=r.useState(!1),[O,K]=r.useState(!1),[xe,F]=r.useState("upload"),[J,$]=r.useState(null),[E,se]=r.useState(null),[M,ae]=r.useState(""),[Le,Ne]=r.useState(!1),[pe,u]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[h,W]=r.useState(null),[w,X]=r.useState(null),[ne,_e]=r.useState(null),Re=r.useRef(!1),[be,c]=r.useState(null),[N,le]=r.useState({}),[d,p]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[I,A]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[H,P]=r.useState([]);r.useEffect(()=>{if(!fe||I.images.length===0){P([]);return}const n=I.images.map((L,te)=>({key:L.name+te,url:URL.createObjectURL(L)}));return P(n),()=>{n.forEach(L=>URL.revokeObjectURL(L.url))}},[fe,I.images]);const we=async()=>{const n=await Nt();l(n)},Oe=async()=>{m(await ms())};r.useEffect(()=>{Promise.all([$t(),Nt(),ms(),zs(20)]).then(([n,L,te,Je])=>{k(n),l(L),m(te);const Ge=Je.find(ze=>["running","canceling"].includes(ze.status))||Je.find(ze=>ze.status!=="preview");_e(Ge||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!O||!(w!=null&&w.id)||!["running","canceling"].includes(w.status))return;const n=window.setInterval(async()=>{if(!Re.current){Re.current=!0;try{const L=await gt(w.id);X(L),_e(L),["running","canceling"].includes(L.status)||(F("done"),await we(),await Oe())}catch(L){console.error("刷新批量铺货进度失败:",L)}finally{Re.current=!1}}},3e3);return()=>{window.clearInterval(n)}},[O,w==null?void 0:w.id,w==null?void 0:w.status]);const $e=async()=>{if(!D)return alert("请先选择账号");Z(!0);try{const n=await rr(D);await we(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{Z(!1)}},Te=n=>{c(n),le({...n}),G(!0)},Ee=async()=>{if(be)try{await hr(be.cookie_id,be.item_id,{item_title:N.item_title||"",item_description:N.item_description||"",item_category:N.item_category||"",item_price:N.item_price||"",item_detail:N.item_detail||be.item_detail||""}),await we(),await Oe(),G(!1),c(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},y=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await nr(n.cookie_id,n.item_id),l(L=>L.filter(te=>!(te.cookie_id===n.cookie_id&&te.item_id===n.item_id)))}catch(L){console.error("删除商品失败:",L),alert("删除失败,请重试")}},C=async()=>{try{if(!d.cookie_id||!d.item_id){alert("请选择账号并填写商品ID");return}await ir(d.cookie_id,{item_id:d.item_id,item_title:d.item_title,item_price:d.item_price,item_detail:d.item_image?JSON.stringify({item_image:d.item_image}):""}),await we(),U(!1),p({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},B=async()=>{if(!I.cookie_id)return alert("请选择发布账号");if(!I.title.trim())return alert("请填写商品标题");if(!I.price.trim())return alert("请填写商品价格");if(!I.quantity||Number(I.quantity)<=0)return alert("库存数量必须大于 0");if(I.images.length===0)return alert("至少上传 1 张商品图片");if(I.postage_mode==="fi Line truncated
`),Je=new Blob(["\uFEFF"+te],{type:"text/csv;charset=utf-8"}),Ge=URL.createObjectURL(Je),ze=document.createElement("a");ze.href=Ge,ze.download="批量铺货模板.csv",document.body.appendChild(ze),ze.click(),ze.remove(),URL.revokeObjectURL(Ge)},re=()=>{p(n=>({...n,cookie_id:D||n.cookie_id})),U(!0)},We=()=>{A(n=>({...n,cookie_id:D||n.cookie_id})),ge(!0)},et=n=>i.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id).length>0?i.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id):i.filter(L=>L.cookie_id===n.cookie_id&&!L.item_id),tt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},it=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Ve=r.useMemo(()=>new Map(v.map(n=>[n.id,n])),[v]),Qe=r.useMemo(()=>R?s.filter(n=>n.cookie_id===R):s,[R,s]),He=n=>{const L=Ve.get(n),te=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return te?`${te} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},pt=n=>{const L=Ve.get(n);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ka,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:R,onChange:n=>f(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),v.map(n=>e.jsx("option",{value:n.id,children:He(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(mt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:D,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),v.map(n=>e.jsx("option",{value:n.id,children:He(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:$e,disabled:Q||!D,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Ue,{className:`w-4 h-4 ${Q?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:re,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(at,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:We,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Kt,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void V(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Tt,{className:"w-4 h-4"}),ne&&["running","canceling"].includes(ne.status)?"继续批量任务":"批量铺货"]}),ne&&!["running","canceling"].includes(ne.status)&&e.jsx("button",{onClick:()=>void Me(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Qe.map(n=>{const L=et(n),te=L.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all gro Line truncated
@@ -1 +0,0 @@
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-wLine truncated
+2 -2
View File
@@ -6,12 +6,12 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-BIyp4is6.js"></script>
<script type="module" crossorigin src="/static/assets/index-DLBJvCyf.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-DjsKcZkz.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-BxxJOyEX.js">
<link rel="stylesheet" crossorigin href="/static/assets/index-DtBcYu3b.css">
<link rel="stylesheet" crossorigin href="/static/assets/index-B8qM55ET.css">
</head>
<body>
<div id="root"></div>
+35 -2
View File
@@ -111,11 +111,14 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string,
}
items := parseItemList(decoded.Data)
totalCount, totalPages := itemListPagination(decoded.Data, pageNumber, pageSize)
return &ItemListResult{
Items: items,
PageNumber: pageNumber,
PageSize: pageSize,
CurrentCount: len(items),
TotalCount: totalCount,
TotalPages: totalPages,
SavedCountHint: len(items),
UpdatedCookies: updated,
}, decoded.Ret, updated, nil
@@ -131,6 +134,7 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS
currentCookies, _, _ = session.State()
}
page := 1
fetchedPages := 0
var all []ItemListItem
for maxPages <= 0 || page <= maxPages {
res, err := c.FetchItemsPage(ctx, currentCookies, page, pageSize)
@@ -139,7 +143,11 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS
}
currentCookies = res.UpdatedCookies
all = append(all, res.Items...)
if len(res.Items) < pageSize {
fetchedPages = page
if res.TotalPages > 0 && page >= res.TotalPages {
break
}
if res.TotalPages <= 0 && len(res.Items) < pageSize {
break
}
page++
@@ -153,12 +161,37 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS
PageSize: pageSize,
CurrentCount: len(all),
TotalCount: len(all),
TotalPages: page,
TotalPages: fetchedPages,
SavedCountHint: len(all),
UpdatedCookies: currentCookies,
}, nil
}
func itemListPagination(data map[string]any, pageNumber, pageSize int) (totalCount, totalPages int) {
for _, key := range []string{"totalCount", "total_count", "total"} {
if value := mtopInt(data[key]); value > 0 {
totalCount = value
break
}
}
for _, key := range []string{"pageCount", "page_count", "totalPages", "total_pages"} {
if value := mtopInt(data[key]); value > 0 {
totalPages = value
break
}
}
if totalPages == 0 && totalCount > 0 && pageSize > 0 {
totalPages = (totalCount + pageSize - 1) / pageSize
}
if totalCount == 0 && totalPages > 0 && pageSize > 0 {
totalCount = totalPages * pageSize
}
if totalPages > 0 && pageNumber > totalPages {
totalPages = pageNumber
}
return totalCount, totalPages
}
func buildItemListQuery(t, sign string) string {
parts := [][2]string{
{"jsv", "2.7.2"},
+27
View File
@@ -227,6 +227,33 @@ func TestFetchAllItemsMultiPage(t *testing.T) {
}
}
func TestFetchAllItemsUsesRemotePageCountWhenPageIsShort(t *testing.T) {
var pageReqs atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
page := pageReqs.Add(1)
if page == 1 {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"pageCount":2,"cardList":[
{"cardData":{"title":"A","detailParams":{"itemId":"i1"}}}
]}}`)
return
}
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"pageCount":2,"cardList":[
{"cardData":{"title":"B","detailParams":{"itemId":"i2"}}}
]}}`)
}))
defer server.Close()
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
res, err := client.FetchAllItems(context.Background(), consignCookies, 20, 10)
if err != nil {
t.Fatalf("err=%v", err)
}
if len(res.Items) != 2 || pageReqs.Load() != 2 {
t.Fatalf("items=%d pageReqs=%d want 2/2", len(res.Items), pageReqs.Load())
}
}
// TestFetchAllItemsMaxPagesCap: maxPages 限制最大页数。
func TestFetchAllItemsMaxPagesCap(t *testing.T) {
var pageReqs atomic.Int32