阶段七:完成 React Feature 化与前置重构收口
This commit is contained in:
1 parent
375e84d663
commit
1a228dc35c
305 files changed
+14179
-5431
No files matched your search
+113
-43
@@ -21,6 +21,7 @@ import (
|
||||
|
||||
"xianyu-go/internal/account"
|
||||
"xianyu-go/internal/adapter"
|
||||
lifecycleapp "xianyu-go/internal/application/lifecycle"
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/browser"
|
||||
@@ -295,10 +296,6 @@ func runServer(parent context.Context, opts serverOptions) error {
|
||||
var bm *browser.Manager
|
||||
if !opts.noBrowser {
|
||||
bm = browser.NewManager(logger)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := bm.Initialize(); err != nil {
|
||||
return fmt.Errorf("初始化 Playwright Chromium 指纹失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ap 保存ap,供当前处理流程使用
|
||||
@@ -308,44 +305,130 @@ func runServer(parent context.Context, opts serverOptions) error {
|
||||
ap.SetChatService(chatService)
|
||||
// mgr 保存mgr,供当前处理流程使用
|
||||
mgr := account.NewManager(store, ap, logger)
|
||||
// autoCenter 保存autoCenter,供当前处理流程使用
|
||||
autoCenter := automation.New(store, mgr, logger)
|
||||
autoCenter.SetOrderDetailFetcher(ap)
|
||||
// notifier 保存notifier,供当前处理流程使用
|
||||
notifier := notify.New("", store, logger)
|
||||
notifier.Start(ctx)
|
||||
autoCenter.SetNotifier(notifier)
|
||||
// autoCenter 保存依赖在启动前固定完成的自动化中心。
|
||||
autoCenter := automation.NewWithDependencies(store, mgr, logger, automation.CenterDependencies{
|
||||
OrderDetailFetcher: ap,
|
||||
Notifier: notifier,
|
||||
})
|
||||
ap.SetAutomation(autoCenter)
|
||||
ap.SetNotifier(notifier)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := mgr.StartAll(ctx); err != nil {
|
||||
logger.Error("启动账号引擎失败", "err", err)
|
||||
}
|
||||
// automationScheduler 保存自动化Scheduler,供当前处理流程使用
|
||||
automationScheduler := automation.NewScheduler(autoCenter)
|
||||
go automationScheduler.Run(ctx)
|
||||
// renewalScheduler 保存renewalScheduler,供当前处理流程使用
|
||||
renewalScheduler := renewal.NewScheduler(store, mgr, ap, logger, notifier)
|
||||
go renewalScheduler.Run(ctx)
|
||||
|
||||
// lifecycleCoordinator 统一拥有应用组件的启动顺序、取消 Context 和逆序关闭。
|
||||
lifecycleCoordinator := lifecycleapp.NewCoordinator()
|
||||
if bm != nil {
|
||||
// err 表示浏览器基础设施组件登记失败。
|
||||
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "browser", Component: lifecycleapp.FuncComponent{
|
||||
StartFunc: func(context.Context) error { return bm.Initialize() },
|
||||
CloseFunc: bm.CloseContext,
|
||||
}}); err != nil {
|
||||
return fmt.Errorf("登记浏览器生命周期组件失败: %w", err)
|
||||
}
|
||||
}
|
||||
// err 表示通知 worker 生命周期组件登记失败。
|
||||
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "notifier", Component: lifecycleapp.FuncComponent{
|
||||
StartFunc: func(componentCtx context.Context) error { notifier.Start(componentCtx); return nil },
|
||||
CloseFunc: notifier.WaitContext,
|
||||
}}); err != nil {
|
||||
return fmt.Errorf("登记通知生命周期组件失败: %w", err)
|
||||
}
|
||||
// err 表示账号运行时生命周期组件登记失败。
|
||||
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "account-manager", Component: lifecycleapp.FuncComponent{
|
||||
StartFunc: mgr.StartAll,
|
||||
CloseFunc: mgr.StopAllContext,
|
||||
}}); err != nil {
|
||||
return fmt.Errorf("登记账号生命周期组件失败: %w", err)
|
||||
}
|
||||
// err 表示自动化调度器生命周期组件登记失败。
|
||||
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "automation-scheduler", Component: lifecycleapp.FuncComponent{
|
||||
StartFunc: func(componentCtx context.Context) error { go automationScheduler.Run(componentCtx); return nil },
|
||||
CloseFunc: automationScheduler.WaitContext,
|
||||
}}); err != nil {
|
||||
return fmt.Errorf("登记自动化调度生命周期组件失败: %w", err)
|
||||
}
|
||||
// err 表示续期调度器生命周期组件登记失败。
|
||||
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "renewal-scheduler", Component: lifecycleapp.FuncComponent{
|
||||
StartFunc: func(componentCtx context.Context) error { go renewalScheduler.Run(componentCtx); return nil },
|
||||
CloseFunc: renewalScheduler.StopContext,
|
||||
}}); err != nil {
|
||||
return fmt.Errorf("登记续期调度生命周期组件失败: %w", err)
|
||||
}
|
||||
|
||||
// srv 是完成依赖校验并注入聊天服务后的 HTTP 应用实例。
|
||||
// serverDependencies 封装 HTTP 服务需要的持久化适配器,避免 Server 直接持有 Store。
|
||||
serverDependencies, dependencyErr := adapter.NewDependencies(store)
|
||||
if dependencyErr != nil {
|
||||
return fmt.Errorf("构造 HTTP 基础设施依赖失败: %w", dependencyErr)
|
||||
// orderDependencies 保存订单应用服务专用的显式装配能力,避免订单路径读取通用设施容器。
|
||||
orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store)
|
||||
if orderDependencyErr != nil {
|
||||
return fmt.Errorf("构造订单基础设施依赖失败: %w", orderDependencyErr)
|
||||
}
|
||||
// accountDependencies 保存账号应用服务专用的显式装配能力,避免账号路径读取通用设施容器。
|
||||
accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store)
|
||||
if accountDependencyErr != nil {
|
||||
return fmt.Errorf("构造账号基础设施依赖失败: %w", accountDependencyErr)
|
||||
}
|
||||
// itemDependencies 保存商品应用服务专用的显式装配能力,避免商品路径读取通用设施容器。
|
||||
itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store)
|
||||
if itemDependencyErr != nil {
|
||||
return fmt.Errorf("构造商品基础设施依赖失败: %w", itemDependencyErr)
|
||||
}
|
||||
// automationDependencies 保存自动化、默认回复和关键词应用服务的显式装配能力。
|
||||
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
|
||||
if automationDependencyErr != nil {
|
||||
return fmt.Errorf("构造自动化基础设施依赖失败: %w", automationDependencyErr)
|
||||
}
|
||||
// miscDependencies 保存通知、分析和卡券应用服务的显式装配能力。
|
||||
miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store)
|
||||
if miscDependencyErr != nil {
|
||||
return fmt.Errorf("构造通知分析卡券基础设施依赖失败: %w", miscDependencyErr)
|
||||
}
|
||||
// adminSettingsDependencies 保存管理员与系统设置应用服务的显式装配能力。
|
||||
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
|
||||
if adminSettingsDependencies == nil {
|
||||
return fmt.Errorf("构造管理员设置基础设施依赖失败")
|
||||
}
|
||||
// chatDependencies 保存聊天应用服务使用的显式运行时与平台适配器。
|
||||
chatDependencies := adapter.NewChatDependencies(store)
|
||||
if chatDependencies == nil {
|
||||
return fmt.Errorf("构造聊天基础设施依赖失败")
|
||||
}
|
||||
// systemDependencies 保存健康检查和订单补偿扫描使用的显式数据库适配器。
|
||||
systemDependencies := adapter.NewSystemDependencies(store)
|
||||
if systemDependencies == nil {
|
||||
return fmt.Errorf("构造系统基础设施依赖失败")
|
||||
}
|
||||
// platformDependencies 保存服务端显式注入的 MTOP、长登录和二维码平台能力。
|
||||
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(logger)
|
||||
if platformDependencyErr != nil {
|
||||
return fmt.Errorf("构造平台基础设施依赖失败: %w", platformDependencyErr)
|
||||
}
|
||||
// authentication 保存 HTTP 会话中间件所需的认证实现;会话 Cookie 的 Secure 策略由启动参数决定。
|
||||
authentication := &auth.Service{Store: store, Logger: logger, Secure: opts.secure}
|
||||
// srv、err 保存 HTTP 服务构造结果及失败原因。
|
||||
srv, err := server.New(serverDependencies, authentication, mgr, opts.webDir, opts.addr, logger, autoCenter, notifier, server.WithChatService(chatService))
|
||||
srv, err := server.New(authentication, mgr, opts.webDir, opts.addr, logger, autoCenter, notifier, server.WithChatService(chatService), server.WithChatDependencies(chatDependencies), server.WithSystemDependencies(systemDependencies), server.WithOrderDependencies(orderDependencies), server.WithAccountDependencies(accountDependencies), server.WithItemDependencies(itemDependencies), server.WithAutomationDependencies(automationDependencies), server.WithMiscDependencies(miscDependencies), server.WithAdminSettingsDependencies(adminSettingsDependencies), server.WithPlatformDependencies(platformDependencies), server.WithApplicationLifecycle(lifecycleCoordinator))
|
||||
if err != nil {
|
||||
return fmt.Errorf("构造 HTTP 服务失败: %w", err)
|
||||
}
|
||||
srv.StartPublishBatchRecovery(ctx)
|
||||
srv.StartOrderReconciliationRecovery(ctx)
|
||||
srv.StartOrderRefreshRecovery(ctx)
|
||||
// component 表示 Server 暴露给进程装配层的一个应用 worker 生命周期组件。
|
||||
for _, component := range srv.ApplicationLifecycleComponents() {
|
||||
// err 表示应用 worker 生命周期组件登记失败。
|
||||
if err := lifecycleCoordinator.Add(component); err != nil {
|
||||
return fmt.Errorf("登记应用 worker 生命周期组件 %q 失败: %w", component.Name, err)
|
||||
}
|
||||
}
|
||||
// err 表示应用组件按依赖顺序启动失败的原因。
|
||||
if err := lifecycleCoordinator.Start(ctx); err != nil {
|
||||
return fmt.Errorf("启动应用生命周期失败: %w", err)
|
||||
}
|
||||
// err 是 HTTP 服务显式启动失败的原因。
|
||||
if err := srv.Start(ctx); err != nil {
|
||||
// rollbackCtx、rollbackCancel 限制 HTTP 启动失败后的组件回滚时间并释放定时器。
|
||||
rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer rollbackCancel()
|
||||
_ = lifecycleCoordinator.Close(rollbackCtx)
|
||||
return fmt.Errorf("启动 HTTP 服务失败: %w", err)
|
||||
}
|
||||
// runErr 是 HTTP 监听退出时返回的错误。
|
||||
@@ -353,30 +436,17 @@ func runServer(parent context.Context, opts serverOptions) error {
|
||||
if runErr != nil {
|
||||
logger.Error("HTTP 服务退出", "err", runErr)
|
||||
}
|
||||
cancel()
|
||||
// stopCtx 是关闭 HTTP 服务及其后台 worker 的有限等待上下文。
|
||||
// stopCtx 是关闭 HTTP 服务及全部应用组件的有限等待上下文。
|
||||
// stopCancel 释放 stopCtx 的定时器资源。
|
||||
// stopCtx、stopCancel 保存stopCtx、stop取消,供当前处理流程使用
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
_ = srv.Stop(stopCtx)
|
||||
// err 表示自动化调度器在关闭上下文内未完成退出的错误。
|
||||
if err := automationScheduler.WaitContext(stopCtx); err != nil {
|
||||
logger.Warn("自动化调度器关闭未完成", "err", err)
|
||||
// err 表示 HTTP 优雅关闭的错误;即使失败也继续关闭应用组件。
|
||||
if err := srv.Stop(stopCtx); err != nil {
|
||||
logger.Warn("HTTP 服务关闭未完成", "err", err)
|
||||
}
|
||||
// err 表示续期调度器在关闭上下文内未完成退出的错误。
|
||||
if err := renewalScheduler.WaitContext(stopCtx); err != nil {
|
||||
logger.Warn("续期调度器关闭未完成", "err", err)
|
||||
}
|
||||
// err 表示账号运行时未能在关闭上下文内完整停止的错误。
|
||||
if err := mgr.StopAllContext(stopCtx); err != nil {
|
||||
logger.Warn("账号运行时关闭未完成", "err", err)
|
||||
}
|
||||
if bm != nil {
|
||||
_ = bm.Close()
|
||||
}
|
||||
// err 表示通知 worker 在关闭上下文内未完成退出的错误。
|
||||
if err := notifier.WaitContext(stopCtx); err != nil {
|
||||
logger.Warn("通知 worker 关闭未完成", "err", err)
|
||||
// err 表示应用组件逆序关闭时的聚合错误;协调器已保证每个组件都会尝试关闭。
|
||||
if err := lifecycleCoordinator.Close(stopCtx); err != nil {
|
||||
logger.Warn("应用组件关闭未完成", "err", err)
|
||||
}
|
||||
stopCancel()
|
||||
return runErr
|
||||
|
||||
@@ -9,6 +9,28 @@
|
||||
- 新增接口必须先进入 `/api/v1/...`,旧路径只有在确认外部调用方为零后才允许删除。
|
||||
- 删除旧路径前必须在本文件记录调用方审计证据、迁移版本和回滚方式,并同步删除对应契约测试。
|
||||
|
||||
## 阶段 3 调用方审计
|
||||
|
||||
旧入口的仓库内调用方由 `tools/architecturecheck` 中的
|
||||
`TestFrontendProductionRequestsUseVersionedAPI` 静态清点,并在每次改动前端请求适配层时运行:
|
||||
|
||||
| 调用方范围 | 当前证据 | 结论与删除条件 |
|
||||
| --- | --- | --- |
|
||||
| React 生产源码(`frontend/**/*.ts`、`frontend/**/*.tsx`,排除测试和构建产物) | 静态扫描未发现未版本化业务请求 | 已迁移到 `/api/v1`;新增调用必须继续通过该门禁 |
|
||||
| React 测试、文档和兼容适配器 | 不作为生产调用方计数 | 可以保留历史样例,但不得被打包到生产请求路径 |
|
||||
| 服务端旧路由 | 各领域版本化契约测试同时请求新旧入口 | 旧路径继续由同一 handler 提供;删除前必须确认外部调用方为零并同步删除契约测试 |
|
||||
| 桌面包、脚本和第三方客户端 | 仓库内无法观测 | 暂不删除;发布侧需要增加请求遥测,连续两个发布周期无调用后才设置 Sunset 版本,并保留回滚版本 |
|
||||
|
||||
该清点只证明仓库内 React 生产请求已经迁移,不能推断外部调用方为零。删除旧路径前,发布说明必须
|
||||
记录调用方审计、Deprecation/Sunset 版本、观测窗口和回滚方式;在证据缺失时保持兼容入口。
|
||||
|
||||
## 受控动态键响应
|
||||
|
||||
`notificationBindingListResponse`(按账号 ID 分组的绑定列表)和
|
||||
`automationRulePageResponse.trigger_counts`(按触发类型统计)是已有客户端依赖的动态键 JSON
|
||||
形状,本阶段不改变字段形状。它们的值类型仍是具名 DTO 或明确标量;架构门禁只允许这类已登记的
|
||||
兼容结构,禁止新增 `map[string]any`、`[]map[string]any` 或未登记的动态响应类型。
|
||||
|
||||
## 仍保留的旧入口
|
||||
|
||||
服务端目前保留 `/api/...`、`/...` 和 `/admin/...` 等历史入口。仓库内生产 React 调用已经全部迁移到 `/api/v1/...`,服务端契约测试仍覆盖新旧路径的等价响应和权限边界。
|
||||
|
||||
@@ -1,27 +1,37 @@
|
||||
# 生命周期与后台任务清单
|
||||
|
||||
本文是重构计划阶段 5 的持续审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界,
|
||||
用于逐项关闭“生命周期与删除 fencing”父切片;清单本身不代表对应组件已经满足完成条件。
|
||||
本文是重构计划阶段 5 收口后的静态审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界,
|
||||
用于防止后续迭代重新引入游离 goroutine;阶段状态和验收证据只记录在重构进度文档中。
|
||||
|
||||
## 组件清单
|
||||
|
||||
| 组件/入口 | 所有者 | Context 来源 | 停止/关闭 | 等待/观测 | 当前证据 | 剩余风险 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| `server.Server` HTTP 与后台任务 | `cmd/server` | `Server.Start` 接收的进程 Context;后台任务继承生命周期 Context | `Server.Stop(ctx)`,关闭 HTTP、恢复任务和后台计数 | `Wait`、`WaitForBackground`、任务注册表状态查询 | Server 生命周期、超时等待和任务注册表测试 | 仍需把所有新后台入口统一登记并审计启动顺序 |
|
||||
| 订单刷新 worker/recovery | `server.Server` | Server 生命周期 Context;恢复扫描使用调用方 Context | worker 终止、租约 fencing、终态写入使用受控 Context | 任务注册表记录 running/succeeded/failed/canceled/timed_out | 订单刷新生命周期与租约测试 | 取消端点和统一运维查询仍待收口 |
|
||||
| 商品批量发布 worker/recovery | `server.Server` | Server 生命周期 Context;取消后的本地收口使用独立补偿 Context | worker cancel、租约 token、批次终态补偿写入 | 任务注册表与批次状态 | 批量取消 race、应用 BatchRunner 测试 | 单行平台适配仍在 Server,恢复指标和统一查询待补齐 |
|
||||
| 订单 reconciliation worker | `server.Server` | Server 生命周期 Context | 扫描器停止时取消当前扫描 | 后台任务注册表和补偿记录状态 | reconciliation 成功/失败重试测试 | 指数退避和更完整运维操作待补齐 |
|
||||
| `account.Manager` 账号运行时集合 | `cmd/server` | `StartAll`/`Start` 调用方 Context | `StopContext`、`StopAllContext`,全局 stopping fence | 等待单账号或全部账号结束 | Manager fencing、删除 fencing 和 race 测试 | 运行时内部任务仍需纳入统一清单 |
|
||||
| `engine.Account` 单账号运行时 | `account.Manager` | `Account.Run(parent)` | `StopContext` 取消运行 Context 并等待连接/任务退出 | `StopContext` 返回错误;运行状态可查询 | Engine lifecycle 与 credential coordinator 测试 | 消息发送、重连和 recorder 子任务需要逐一核对 Join 边界 |
|
||||
| 浏览器 `Manager` | `cmd/server`/账号流程 | 每次调用的 Context;关闭使用 `CloseContext` | 关闭 fencing,等待活动调用归零,再关闭 Playwright | `CloseContext` 返回超时并可重试 | Browser lifecycle 与 race 测试 | 底层同步 Playwright Close 无法被 Context 中断 |
|
||||
| 续期 `renewal.Scheduler` | `cmd/server` | `Run(ctx)` 调用方 Context | `StopContext` 幂等并阻止 Stop 后 Run | `WaitContext` | 先 Stop、重复 Stop、零值和 race 测试 | 迟到 Cookie 合并调用方仍需统一审计 |
|
||||
| 自动化 `automation.Scheduler` | `cmd/server` | `Run(ctx)` 调用方 Context | Context 取消后停止调度 | `WaitContext` | scheduler 与结果收口测试 | 自动化准备和外部动作旁路仍需完整盘点 |
|
||||
| 通知 outbox worker | `cmd/server` | `Start(ctx)` 调用方 Context | Context 取消后停止拉取与发送 | `WaitContext`、uncertain 状态查询 | notify worker、uncertain 状态和三库测试 | 运维重试与人工核对流程仍待补齐 |
|
||||
| WebSocket/聊天后台发送任务 | `server.Server`/`chat.Service` | 请求或服务生命周期 Context | 请求取消、连接关闭或服务停止;handler 清理阶段先取消并关闭连接 | handler 等待读取 goroutine 退出,发送结果和连接状态仍由连接生命周期观测 | WebSocket 事件流测试、Server race;`chatWebSocket` 已显式 Wait/Join 读取任务 | 其他实时连接的统一 owner/Join 证据仍待完善 |
|
||||
| `server.Server` HTTP 与请求后台任务 | `cmd/server`(HTTP)/`server.Server`(请求任务观测) | `Server.Start` 接收的进程 Context;请求任务使用调用方显式 Context | `Server.Stop(ctx)` 只关闭 HTTP 与请求任务等待;应用 worker 不由 Server 关闭 | `Wait`、`WaitForBackground`、任务注册表状态查询 | Server 生命周期、超时等待和任务注册表测试 | 业务 worker 已移出 Server;任务业务语义继续由应用服务维护 |
|
||||
| 订单刷新 worker/recovery | `lifecycle.Coordinator` → `orders.RefreshJobService` | 协调器共享应用生命周期 Context;请求只负责创建任务 | 协调器逆序 `Close(ctx)`,runner 通过租约 token 和 Context 收束 | 应用任务状态、租约终态和 runner `Wait/Close` | 订单刷新生命周期、租约、取消和晚到写入测试 | 统一运维查询属于后续观测迭代,不改变生命周期所有权 |
|
||||
| 商品批量发布 worker/recovery | `lifecycle.Coordinator` → `items.BatchWorkerCoordinator` | 协调器共享应用生命周期 Context;取消后的本地收口使用受控补偿 Context | 协调器逆序 `Close(ctx)`,worker cancel、租约 token 和终态补偿由应用协调器负责 | 批次状态、协调器 `Wait/Close` 与错误回调 | 批量取消 race、应用 BatchRunner 和协调器测试 | 恢复指标属于后续观测迭代,不改变生命周期所有权 |
|
||||
| 订单 reconciliation worker | `lifecycle.Coordinator` → `orders.ReconciliationRecoveryCoordinator` | 协调器共享应用生命周期 Context | 协调器逆序 `Close(ctx)` 取消当前扫描并等待退出 | 补偿记录状态与协调器 `Wait/Close` | reconciliation 成功/失败重试、取消和协调器测试 | 指数退避属于后续补偿策略迭代 |
|
||||
| `account.Manager` 账号运行时集合 | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopAllContext`,保留全局 stopping fence | 等待单账号或全部账号结束 | Manager fencing、删除 fencing、生命周期和 race 测试 | 运行时内部任务的细分归入阶段 6,不改变进程级 owner |
|
||||
| `engine.Account` 单账号运行时 | `account.Manager`;连接、出站、凭证和迟到续期分别由 `connectionCoordinator`、`outgoingMessageCoordinator`、`credentialCoordinator`、`pendingRenewalCoordinator` 负责 | `Account.Run(parent)` | `StopContext` 取消运行 Context;连接协调器以受限预算等待自有 worker | `StopContext` 返回错误;共享完成信号支持超时后的再次 Join;运行状态可查询 | Engine lifecycle、连接协调器、出站发送、credential coordinator、刷新取消与迟到续期测试 | recorder 子任务继续沿用账号运行 Context,不允许脱离 facade 生命周期 |
|
||||
| 浏览器 `Manager` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 每次调用的独立 Context;初始化和关闭受协调器 Context/Close Context 约束 | 协调器逆序调用 `CloseContext`,关闭 fencing 并等待活动调用归零 | `CloseContext` 返回超时并可重试 | Browser lifecycle 与 race 测试 | 底层同步 Playwright Close 无法被 Context 中断,这是实现约束 |
|
||||
| 续期 `renewal.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopContext`,幂等并阻止 Stop 后 Run | `WaitContext` | 先 Stop、重复 Stop、零值和 race 测试 | 迟到 Cookie 合并语义由续期组件自身 generation/锁测试保护 |
|
||||
| 自动化 `automation.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序取消 Context 并调用 `WaitContext` | `WaitContext` | scheduler 与结果收口测试 | 自动化外部动作语义归入阶段 6,不改变调度器 owner |
|
||||
| 通知 outbox worker | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `WaitContext`,由共享 Context 停止拉取与发送 | `WaitContext`、uncertain 状态查询 | notify worker、uncertain 状态和三库测试 | 运维重试与人工核对流程属于通知业务迭代 |
|
||||
| WebSocket/聊天后台发送任务 | `chat.Service` 与请求级连接 owner | 请求 Context 和连接关闭信号;不继承 Server 业务 worker Context | 请求取消或连接关闭时先取消发送/读取任务,再由连接 owner 等待 Join | WebSocket handler 显式等待读取 goroutine,发送结果和连接状态保留可观测字段 | WebSocket 事件流测试、Server race;`chatWebSocket` 已显式 Wait/Join 读取任务 | 更细的消息分发状态拆分属于阶段 6,不新增 Server 生命周期入口 |
|
||||
|
||||
## 阶段 6 并发与锁边界
|
||||
|
||||
| 锁/协调状态 | 所有者与保护范围 | 明确禁止 | 锁顺序/验证 |
|
||||
| --- | --- | --- | --- |
|
||||
| `Store` 账号凭证锁 | 保护 Cookie、metadata、Token 绑定指纹的快照读取和条件写回 | 不得跨 MTOP、WebSocket、浏览器、通知或用户等待 I/O | `refreshGate → credential lock`;锁外 I/O、旧响应冲突和锁外 Handler 通知测试 |
|
||||
| Engine `refreshGate` | 用单令牌通道串行化同一账号 Token/续期状态机及迟到响应收口,不持有互斥锁等待外部 I/O | 不得反向取得其他 worker 锁;等待必须响应调用 Context 取消 | `refreshGate → credential lock`;Token、API 续期、迟到 Cookie、取消和 race 测试 |
|
||||
| Engine `outgoingMessageCoordinator` | 先短暂读取 `runtimeMu` 中的连接,再短暂读取凭证锁中的 `unb` 身份;发送与历史查询在两把锁外执行 | 不得同时持有 `runtimeMu` 与凭证锁,不得持锁执行 WebSocket I/O | `runtime snapshot → credential snapshot`,两段锁不重叠;出站发送与连接 race 测试 |
|
||||
| Automation `cardLocks` | 保护同一卡密组库存消费与确定未发送时恢复 | 不得覆盖 WebSocket 消息发送、图片发送或人工等待 | 每次库存操作独立加锁;并发卡密发送阻塞测试 |
|
||||
| Automation 运行租约/动作检查点 | 由数据库租约拥有跨进程 worker 的唯一执行权;结果通知以 `runID + status` 写入持久化 outbox | 不得在本地互斥锁内持有外部动作;不确定结果不得自动重放或重新入队 | `StartRunAction` 后执行外部动作;通知 outbox 的成功/失败/不确定隔离与重复恢复测试 |
|
||||
|
||||
## 使用规则
|
||||
|
||||
1. 新增 goroutine 必须在本表增加一行,注明启动者、Context 来源、取消责任和等待方式。
|
||||
2. 每个组件完成生命周期迁移后,必须同时提供取消、超时、重复停止和晚到写入测试;测试通过不等于其他组件自动完成。
|
||||
2. 新组件必须同时提供取消、超时、重复停止和晚到写入测试;测试通过不等于其他组件自动继承其业务语义。
|
||||
3. 删除账号前必须先建立账号级 stopping fence,再在受限 Context 内停止运行时,最后重新校验归属并删除持久化记录。
|
||||
4. 本表中标记为“剩余风险”的项目未满足父切片关闭条件前,阶段 5 必须保持“进行中”。
|
||||
4. 本表只记录 owner 与边界;阶段 6 以后业务策略、运维观测和实时连接细分风险不得重新转化为 Server 生命周期入口。
|
||||
@@ -58,16 +58,20 @@ React app shell
|
||||
空列表编码为 `[]`,前端同时接受数组、包裹对象和 `null`;对应回归测试是强制契约。
|
||||
- 远端 `main` 的文档链接变更不影响运行功能。生成前端资产的文本冲突必须通过当前源码重新构建
|
||||
解决,禁止手工合并压缩产物。
|
||||
- Server 生产代码已大幅迁移到应用 Port,架构检查当前可通过;但仍存在 Server 暴露
|
||||
`*sql.Tx` 的遗留事务边界、Server 持有业务 worker/会话状态,以及集中式依赖工厂隐藏底层
|
||||
`Store` 的风险,因此阶段 4 和阶段 5 尚未验收。
|
||||
- Server 生产代码已迁移到应用 Port,架构检查当前可通过;阶段 4 已移除 Server 暴露
|
||||
`*sql.Tx` 的遗留事务边界,并将订单刷新任务、订单补偿扫描、批量发布 worker、扫码会话、账号登录、
|
||||
商品、聊天、通知、分析、卡券、自动化和管理员设置装配下沉到应用服务与显式类型化依赖。Session 恢复、
|
||||
订单运行时 typed port 和账号凭证恢复协调也已完成,已知调用方不再依赖集中式 `adapter.Dependencies`;
|
||||
阶段 4 与阶段 5 已完成。
|
||||
- 账号敏感摘要与秘密访问已经分离,并已有审计和多数据库覆盖;阶段 2 可视为完成,但后续迭代
|
||||
不得重新扩大读取、解密、序列化或日志范围。
|
||||
- HTTP 已有 `/api/v1` 路径和兼容契约测试,但 transport 仍使用动态 map、部分兼容响应别名和
|
||||
未生成的集中类型,因此阶段 3 尚未验收。
|
||||
- Engine `Account`、Automation `Center`、集中前端 API/类型文件和若干大型 Hook 仍承担过多职责;
|
||||
目录已经拆分不等于对应阶段完成。
|
||||
- 生命周期清单仍列有 Engine 子任务、实时连接、恢复任务和运维观测缺口;阶段 5 尚未验收。
|
||||
- HTTP `/api/v1` 版本化、具名 DTO、统一错误、前端兼容归一和调用方审计已完成阶段 3 验收;
|
||||
受控的设置键、账号绑定键和触发统计键仍按兼容清单保留,删除条件记录在
|
||||
`docs/architecture/api-compatibility-matrix.md`。
|
||||
- Engine `Account` 与 Automation `Center` 已收束为稳定 facade;连接、出站消息、凭证、运行检查点、
|
||||
动作执行、库存、通知和迟到续期分别由明确组件拥有。集中前端 API/类型文件和若干大型 Hook
|
||||
仍属于阶段 7 的后续范围。
|
||||
- 阶段 5 已完成进程级应用装配与生命周期收口;生命周期清单保留 Engine/Automation 内部状态拆分和运维观测等后续阶段风险,但不再允许回流为 Server 或 cmd 的隐式后台入口。
|
||||
- 三方言迁移编号当前对齐,订单已有游标和批量写入能力;跨 repository 事务、查询计划、补偿和
|
||||
大数据量行为仍需阶段 8 统一验收。
|
||||
- 注释历史基线文件当前为空,但源码仍存在“保存 X 供当前流程使用”等模板化注释。机械基线清零
|
||||
@@ -85,12 +89,12 @@ React app shell
|
||||
| 0. 治理与强约束 | 前置完成 | 建立计划、依赖、注释、冻结规范和自动检查 |
|
||||
| 1. CI 与测试基础 | 已完成 | 建立独立 CI、分层 race 和三数据库门禁 |
|
||||
| 2. 敏感数据访问边界 | 已完成 | 分离摘要、平台凭证、登录秘密和敏感设置 |
|
||||
| 3. HTTP API 契约 | 当前迭代 | 完成版本化、具名 DTO、统一错误和前端契约 |
|
||||
| 4. Server 应用服务 | 待执行 | 把完整业务用例和事务边界移出 transport |
|
||||
| 5. 应用装配与生命周期 | 待执行 | 消除隐式装配、业务 worker 和游离后台任务 |
|
||||
| 6. Engine 与 Automation | 待执行 | 将大 facade 拆为有明确状态所有权的组件 |
|
||||
| 7. React Feature 化 | 待执行 | 完成 feature 边界、请求归属、状态和按路由加载 |
|
||||
| 8. DB 与事务治理 | 待执行 | 完成窄 repository、Unit of Work 和三方言验收 |
|
||||
| 3. HTTP API 契约 | 已完成 | 完成版本化、具名 DTO、统一错误和前端契约 |
|
||||
| 4. Server 应用服务 | 已完成 | 把完整业务用例和事务边界移出 transport |
|
||||
| 5. 应用装配与生命周期 | 已完成 | 消除隐式装配、业务 worker 和游离后台任务 |
|
||||
| 6. Engine 与 Automation | 已完成 | 将大 facade 拆为有明确状态所有权的组件 |
|
||||
| 7. React Feature 化 | 已完成 | 完成 feature 边界、请求归属、状态和按路由加载 |
|
||||
| 8. DB 与事务治理 | 当前迭代 | 完成窄 repository、Unit of Work 和三方言验收 |
|
||||
| 9. 架构门禁与兼容退场 | 待执行 | 封死依赖旁路并按 Sunset 删除兼容层 |
|
||||
| 10. 注释与复杂度收口 | 待执行 | 清除模板注释和复杂度债务,形成最终质量门禁 |
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
# 重构阶段验收记录
|
||||
|
||||
本文件只记录阶段整体的验收证据、更新日志和阶段边界。每个阶段对应一个 PR;阶段内并行实现不形成独立任务、独立验收或额外 PR。
|
||||
|
||||
## 阶段 3:HTTP API 契约
|
||||
|
||||
状态:已完成。
|
||||
|
||||
主要证据:业务入口使用 `/api/v1` 版本化路径、具名 DTO、统一错误 envelope 和前端兼容归一;空集合兼容、契约测试、前端构建和嵌入资源均已验证。
|
||||
|
||||
## 阶段 4:Server 应用服务
|
||||
|
||||
状态:已完成;对应一个阶段 4 PR 边界。
|
||||
|
||||
完成证据:
|
||||
|
||||
- Server 生产代码不再导入 `database/sql`、`internal/db`、`internal/xianyu` 或 `internal/browser`,不创建事务,也不持有通用 `adapter.Dependencies`。
|
||||
- 订单刷新、订单补偿扫描、批量发布、二维码会话、账号登录、Cookie 写入、资料刷新、聊天刷新/订阅、商品发布和管理员删除均通过应用服务与消费者定义的最小 Port 编排。
|
||||
- Session 失效恢复统一由 `adapter.SessionRecoveryHandler` 分类和记录脱敏诊断,再调用账号运行时应用端口;生产适配器不再把 `Server.recoverExpiredMTOPSession` 作为回调传入。
|
||||
- 订单运行时使用 `adapter.OrderAutomation`、`adapter.OrderNotifier` 等 typed port;Server 不再编排 Manager、Automation 和 Notifier 闭包。订单补偿扫描由 `orders.ReconciliationRecoveryCoordinator` 拥有启动、取消、等待和关闭生命周期。
|
||||
- 账号凭证恢复使用 `account.CredentialRefreshCoordinator` 按账号并发登记;慢速协议续期不在协调锁内执行,自动化唤醒经过 `CredentialWakePort`/`CredentialWakeService`。
|
||||
- 所有必需领域依赖由显式类型化依赖组构造并在 `Server.New` 阶段校验;缺失依赖、越权、失败、取消、重复启动/关闭、租约 fencing、补偿和晚到结果均有聚焦测试。
|
||||
- `MTop`、`CookieRenew`、`QRLogin` 以及少量 Adapter setter 仅作为测试/兼容入口保留。删除条件为已知生产与测试调用清零、契约测试证明新构造路径覆盖全部调用,并完成外部调用方审计;这些兼容入口不作为新增业务依赖。
|
||||
- 冻结滑块 CAPTCHA 实现及其测试未修改。
|
||||
|
||||
统一验证证据:
|
||||
|
||||
```text
|
||||
go test ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||
go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||
go vet ./...
|
||||
go run ./tools/architecturecheck
|
||||
go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json
|
||||
git diff --check
|
||||
```
|
||||
|
||||
以上命令均通过;race 运行实际覆盖应用层、适配器和 Server 生命周期/凭证并发路径。
|
||||
|
||||
## 更新日志
|
||||
|
||||
- 2026-08-17:完成阶段 4 整体 Server 应用服务改造,统一完成应用 Port、显式装配、凭证边界、Session 恢复、订单补偿生命周期和并发协调,并通过阶段 4 全部门禁。
|
||||
|
||||
## 阶段 5:应用装配与生命周期
|
||||
|
||||
状态:已完成;对应一个阶段 5 PR 边界。阶段内并行实现不形成独立任务、独立验收或额外 PR。
|
||||
|
||||
完成证据:
|
||||
|
||||
- 新增 `internal/application/lifecycle.Coordinator`,统一拥有共享 Context、登记顺序、启动失败逆序回滚、关闭逆序、并发 Close 等待、超时和错误聚合;组件回调始终在锁外执行。
|
||||
- `cmd/server` 统一登记浏览器、Notifier、账号 Manager、Automation Scheduler、Renewal Scheduler 以及订单刷新、批量发布、订单 reconciliation 三类应用 worker;HTTP Server 只负责 HTTP 启停,退出时先停 HTTP,再由协调器逆序关闭应用组件。
|
||||
- Server 删除业务 worker 的启动/关闭入口和应用 worker 等待逻辑;Server 仅通过只读生命周期 Context 为请求创建的应用 worker 提供父 Context,生命周期 owner 保持在协调器与应用服务。
|
||||
- 启动失败回滚、重复 Start/Close、并发 Close、启动与关闭竞争、批次/订单 worker 取消、租约 fencing、账号 stopping fence、浏览器关闭超时重试和实时连接 Join 均有聚焦测试;冻结 CAPTCHA 文件未修改。
|
||||
- `docs/architecture/lifecycle-inventory.md` 已转为静态 owner/Context/Stop/Wait 清单,后续 Engine/Automation 内部状态拆分和运维观测风险归入阶段 6 及后续迭代,不得重新引入 Server 生命周期入口。
|
||||
|
||||
统一验证证据:
|
||||
|
||||
```text
|
||||
make check
|
||||
go test -race ./internal/server ./internal/account ./internal/engine ./internal/automation ./internal/renewal -count=1
|
||||
go test ./... -count=1
|
||||
go run ./tools/architecturecheck
|
||||
go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json
|
||||
git diff --check
|
||||
```
|
||||
|
||||
以上命令均通过;race 子集实际覆盖 Server、账号、Engine、Automation、续期和生命周期竞争路径。
|
||||
|
||||
下一安全入口:阶段 6「Engine 与 Automation」,只处理其内部状态所有权和动作语义拆分,不回退或扩大阶段 5 的进程生命周期边界。
|
||||
|
||||
## 更新日志
|
||||
|
||||
- 2026-08-17:完成阶段 5 应用装配与生命周期整体改造,统一 cmd 生命周期协调、Server HTTP 边界、应用 worker owner、启动回滚与关闭等待,并通过阶段 5 全部门禁。
|
||||
|
||||
## 阶段 6:Engine 与 Automation
|
||||
|
||||
状态:已完成;对应一个阶段 6 PR 边界。阶段内并行实现不形成独立任务、独立验收或额外 PR。
|
||||
|
||||
完成证据:
|
||||
|
||||
- `automationActionExecutor.sendDataCard` 的卡券锁仅覆盖库存预留与确定未发送时的恢复,外部 WebSocket 发送已移到锁外,并有并发阻塞测试证明第二个库存操作不会等待第一个外部发送。
|
||||
- `confirmShipmentAttempt` 在凭证锁内只读取最小运行时快照,MTOP 调用在锁外执行;响应写回重新获取凭证锁并进行指纹条件校验,冲突时跳过旧响应并记录人工核对所需错误。
|
||||
- 新增凭证锁锁外外部 I/O、并发新凭证不被旧响应覆盖的确定性测试;冻结 CAPTCHA 实现及测试未修改。
|
||||
- `automation.NewWithDependencies` 固定 MTOP、账号任务、订单详情、通知和 Cookie 读取依赖;所有 `Center` setter、运行时依赖覆盖和其锁已删除,延迟恢复通过同一构造依赖重建 Center。
|
||||
- `engine.Account` 已将连接、出站消息、凭证、消息分发、运行状态、生命周期和迟到续期收束到独立组件;凭证实现已物理迁入 `credentialCoordinator`,facade 仅保留稳定入口和必要兼容委托。
|
||||
- `refreshGate` 支持 Context 取消;凭证锁只覆盖快照和条件提交,MTOP、WebSocket、浏览器、通知及 Handler 回调均在锁外执行。`pendingRenewalCoordinator` 与连接协调器以共享完成信号和有限预算 Join,不创建超时后无法回收的等待 goroutine。
|
||||
- 自动化外部动作在运行检查点后执行,保留成功、失败和 `needs_review` 三态。结果通知以 `runID + status` 作为持久化 outbox 幂等键,重复恢复不会重复入队;外部投递成功但本地确认失败的 `uncertain` 记录不会自动重放。SQLite、MySQL、PostgreSQL 的 `00034` 通知幂等迁移已对齐。
|
||||
- 冻结 CAPTCHA 受保护文件未改动;浏览器集成和全部冻结行为测试通过。
|
||||
|
||||
下一安全入口:阶段 7「React Feature 化」。仅处理 `app -> features -> shared`、feature API adapter、状态归属与路由加载,不回退阶段 6 的 Engine、Automation、凭证、通知或并发边界。
|
||||
|
||||
当前统一验证证据:
|
||||
|
||||
```text
|
||||
make check # 通过
|
||||
go test ./internal/engine ./internal/automation ./internal/browser -count=1 # 通过
|
||||
go test -race ./internal/engine ./internal/automation -count=1 # 通过
|
||||
RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1 # 通过
|
||||
go run ./tools/architecturecheck # 通过
|
||||
make comments # 通过
|
||||
git diff --check # 通过
|
||||
make cover # Go statements 66.5%
|
||||
make cover-browser # Browser statements 60.9%(RUN_BROWSER_INTEGRATION=1)
|
||||
make cover-frontend # Frontend statements 93.01%
|
||||
```
|
||||
|
||||
覆盖率例外:未跳过本地确定性 Engine、Automation 或浏览器行为;仅保留项目既有的真实账号/外部平台不可用场景分类。
|
||||
|
||||
更新日志:
|
||||
|
||||
- 2026-08-17:完成阶段 6 整体 Engine 与 Automation 改造,统一收束 facade、凭证和 worker 生命周期、锁外外部 I/O、运行检查点及通知幂等/不确定态,并通过阶段 6 全部门禁。
|
||||
|
||||
## 阶段 7:React Feature 化
|
||||
|
||||
状态:已完成;对应一个阶段 7 PR 边界。阶段内并行实现不形成独立任务、独立验收或额外 PR。
|
||||
|
||||
完成证据:
|
||||
|
||||
- 根 `App` 仅装配错误边界、会话 Provider 和路由;认证表单归属 session feature,认证后导航、权限回退、侧边栏偏好和一次性跨页面载荷由 app 路由壳管理。
|
||||
- 九个业务页面与其直属组件、Hook、状态、API adapter 和测试均归入各自 feature;账号自动任务归入 accounts,删除跨 feature 的 accountAutomation 目录。
|
||||
- 已删除集中式 `frontend/services/api.ts`、`frontend/types.ts`、`frontend/request.ts` 和 `frontend/services/contract.ts`;feature API adapter 直接依赖 `shared/http`,只读传输契约位于 `shared/api-contract`,DTO 归一保留在所属 feature 边界。
|
||||
- `shared` 只保留 HTTP transport、兼容 JSON contract、通用异步 gate、浏览器偏好和纯展示 UI;架构测试禁止 feature 相互导入、shared 反向依赖 feature、组件直连网络和根 components 回流。
|
||||
- 所有业务页面由 `React.lazy` 按路由加载;构建验证九个独立页面分片、首屏不预加载 charts 分片且每页原始大小满足既有预算。仪表盘乱序、卡密/订单卸载取消、聊天切换与旧分页响应均有确定性行为测试。
|
||||
- 冻结 CAPTCHA 实现、测试及调用语义均未修改。
|
||||
|
||||
当前统一验证证据:
|
||||
|
||||
```text
|
||||
npm test --prefix frontend # 63 files, 383 tests 通过
|
||||
npm run typecheck --prefix frontend # 通过
|
||||
npm run comments:check --prefix frontend # 通过
|
||||
npm run build --prefix frontend # 通过,已更新 internal/webui/static
|
||||
make cover-frontend # Frontend statements 79.84%,RUN_BROWSER_INTEGRATION 未使用
|
||||
git diff --check # 通过
|
||||
go run ./tools/architecturecheck # 通过
|
||||
make comments # 通过
|
||||
make check # 通过
|
||||
```
|
||||
|
||||
覆盖率例外:纯 React 页面、展示组件与错误边界在本阶段的 V8 报告中存在未覆盖行;所有新改动的业务 API、Hook、状态、取消、切换和乱序行为均由确定性 Vitest 覆盖。无真实账号或外部平台调用。
|
||||
|
||||
下一安全入口:阶段 8「DB 与事务治理」,仅处理窄 repository、应用层 Unit of Work、批量与三方言事务验收;不得回退阶段 7 的 feature 边界、共享 HTTP 或路由加载约束。
|
||||
|
||||
更新日志:
|
||||
|
||||
- 2026-08-17:完成阶段 7 React Feature 化整体改造,统一落地 app -> features -> shared、feature API adapter、路由懒加载、异步请求生命周期与前端架构门禁,并通过阶段全部验证。
|
||||
+10
-299
@@ -1,304 +1,15 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState';
|
||||
import { YdisksBrandIcon } from './components/YdisksLogo';
|
||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
||||
import AuthenticatedShell, { type DeliveryRuleTarget } from './app/shell/AuthenticatedShell';
|
||||
import { SessionProvider, useSession } from './app/providers/SessionProvider';
|
||||
import React from 'react';
|
||||
import { AppErrorBoundary } from './app/errors/AppErrorBoundary';
|
||||
import { SessionProvider } from './app/providers/SessionProvider';
|
||||
import { AppRouter } from './app/router/AppRouter';
|
||||
|
||||
// 路由:URL path ↔ tab id。所有 SPA 路由统一挂 /app/ 前缀,避免和后端 API
|
||||
// 路径(/orders、/cards、/items 等)冲突——后者在 chi 里先注册,刷新会直接
|
||||
// 返回 JSON 而不是 SPA 页面。
|
||||
const ROUTES: Record<string, string> = {
|
||||
'/app/dashboard': 'dashboard',
|
||||
'/app/accounts': 'accounts',
|
||||
'/app/chat': 'chat',
|
||||
'/app/orders': 'orders',
|
||||
'/app/cards': 'cards',
|
||||
'/app/items': 'items',
|
||||
'/app/rules': 'rules',
|
||||
'/app/notifications': 'notifications',
|
||||
'/app/settings': 'settings',
|
||||
};
|
||||
const TAB_TO_PATH: Record<string, string> = Object.fromEntries(
|
||||
Object.entries(ROUTES).map(([path, tab]) => [tab, path] /* 回调函数负责当前业务流程。 */)
|
||||
); /* TAB_TO_PATH 表示TABTO当前路径。 */
|
||||
const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard'; /* tabFromPath 表示tabFrom当前路径。 */
|
||||
|
||||
// AppView 渲染认证表单、路由状态和认证成功后的应用壳。
|
||||
const AppView: React.FC = () => {
|
||||
// session 从 Provider 读取认证状态和会话操作,避免页面直接管理全局会话副作用。
|
||||
const { checkingAuth, isLoggedIn, isAdmin, needsInit, signIn, initialize, signOut } = useSession();
|
||||
const [activeTab, setActiveTab] = useState(tabFromPath); /* [activeTab, setActiveTab] 表示activeTabsetActiveTab。 */
|
||||
const [username, setUsername] = useState(''); /* [username, setUsername] 表示usernamesetUsername。 */
|
||||
const [password, setPassword] = useState(''); /* [password, setPassword] 表示passwordsetPassword。 */
|
||||
const [loginLoading, setLoginLoading] = useState(false); /* [loginLoading, setLoginLoading] 表示login加载状态setLogin加载状态。 */
|
||||
const [loginError, setLoginError] = useState(''); /* [loginError, setLoginError] 表示login当前操作返回的错误setLogin当前操作返回的错误。 */
|
||||
const [initialPassword, setInitialPassword] = useState(''); /* [initialPassword, setInitialPassword] 表示initialPasswordsetInitialPassword。 */
|
||||
const [initialPasswordConfirm, setInitialPasswordConfirm] = useState(''); /* [initialPasswordConfirm, setInitialPasswordConfirm] 表示initialPasswordConfirmsetInitialPasswordConfirm。 */
|
||||
const [initializing, setInitializing] = useState(false); /* [initializing, setInitializing] 表示initializingsetInitializing。 */
|
||||
const [initializationError, setInitializationError] = useState(''); /* [initializationError, setInitializationError] 表示initialization当前操作返回的错误setInitialization当前操作返回的错误。 */
|
||||
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>(); /* [deliveryRuleTarget, setDeliveryRuleTarget] 表示delivery当前规则TargetsetDelivery当前规则Target。 */
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed); /* [sidebarCollapsed, setSidebarCollapsed] 表示sidebarCollapsedsetSidebarCollapsed。 */
|
||||
|
||||
// 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。
|
||||
const navigate = (tab: string) => {
|
||||
const nextTab = tab === 'settings' && !isAdmin ? 'dashboard' : tab; /* nextTab 表示nextTab。 */
|
||||
const path = TAB_TO_PATH[nextTab]; /* path 表示当前路径。 */
|
||||
if (path && path !== window.location.pathname) {
|
||||
window.history.pushState({}, '', path);
|
||||
}
|
||||
setActiveTab(nextTab);
|
||||
};
|
||||
|
||||
// 浏览器后退/前进同步 tab。
|
||||
useEffect(() => {
|
||||
const onPopState = () => setActiveTab(tabFromPath()); /* onPopState 表示onPopState。 */
|
||||
window.addEventListener('popstate', onPopState);
|
||||
return () => window.removeEventListener('popstate', onPopState) /* 回调函数负责当前业务流程。 */;
|
||||
} /* 回调函数负责当前业务流程。 */, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!checkingAuth && isLoggedIn && !isAdmin && activeTab === 'settings') {
|
||||
window.history.replaceState({}, '', TAB_TO_PATH.dashboard);
|
||||
setActiveTab('dashboard');
|
||||
}
|
||||
} /* 回调函数负责当前业务流程。 */, [checkingAuth, isLoggedIn, isAdmin, activeTab]);
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoginLoading(true);
|
||||
setLoginError('');
|
||||
|
||||
try {
|
||||
const res = await signIn({ username, password }); /* res 表示接口响应结果。 */
|
||||
if (!res.success) {
|
||||
setLoginError(res.message || '登录失败');
|
||||
}
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
const msg = err instanceof Error ? err.message : String(err); /* msg 表示msg。 */
|
||||
setLoginError(msg || '登录失败');
|
||||
} finally {
|
||||
setLoginLoading(false);
|
||||
}
|
||||
}; /* handleLogin 表示handleLogin。 */
|
||||
|
||||
const handleInitialize = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setInitializationError('');
|
||||
if (initialPassword.length < 8) {
|
||||
setInitializationError('密码至少需要 8 个字符');
|
||||
return;
|
||||
}
|
||||
if (initialPassword !== initialPasswordConfirm) {
|
||||
setInitializationError('两次输入的密码不一致');
|
||||
return;
|
||||
}
|
||||
|
||||
setInitializing(true);
|
||||
try {
|
||||
const res = await initialize(initialPassword); /* res 表示接口响应结果。 */
|
||||
if (!res.success) {
|
||||
setInitializationError(res.message || '初始化失败,请重试');
|
||||
return;
|
||||
}
|
||||
setInitialPassword('');
|
||||
setInitialPasswordConfirm('');
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
const msg = err instanceof Error ? err.message : String(err); /* msg 表示msg。 */
|
||||
setInitializationError(msg || '初始化失败,请重试');
|
||||
} finally {
|
||||
setInitializing(false);
|
||||
}
|
||||
}; /* handleInitialize 表示handleInitialize。 */
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await signOut();
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
console.error('退出登录失败', err);
|
||||
}
|
||||
}; /* handleLogout 表示handleLogout。 */
|
||||
|
||||
|
||||
if (checkingAuth) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-surface">
|
||||
<Loader2 className="w-8 h-8 text-brand animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Init Screen (system not initialized)
|
||||
if (needsInit) {
|
||||
return (
|
||||
<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-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" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">首次设置管理员密码</h2>
|
||||
<p className="text-gray-600 font-medium">设置完成后会自动进入系统,管理员账号为 admin。</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleInitialize} className="space-y-5">
|
||||
<div className="space-y-4">
|
||||
<div className="relative group">
|
||||
<Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
||||
<input
|
||||
type="password"
|
||||
placeholder="设置管理员密码(至少 8 个字符)"
|
||||
value={initialPassword}
|
||||
onChange={e => setInitialPassword(e.target.value) /* 回调函数负责当前业务流程。 */}
|
||||
autoFocus
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative group">
|
||||
<ShieldCheck className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
||||
<input
|
||||
type="password"
|
||||
placeholder="再次输入密码"
|
||||
value={initialPasswordConfirm}
|
||||
onChange={e => setInitialPasswordConfirm(e.target.value) /* 回调函数负责当前业务流程。 */}
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{initializationError && (
|
||||
<div className="p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2">
|
||||
<ShieldCheck className="w-4 h-4" /> {initializationError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={initializing}
|
||||
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70"
|
||||
>
|
||||
{initializing ? <Loader2 className="w-5 h-5 animate-spin" /> : <>设置密码并进入系统 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /></>}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="mt-8 pt-6 border-t border-gray-100 text-center">
|
||||
<span className="text-xs text-gray-400 font-medium tracking-widest uppercase">Secure Bootstrap</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Login Screen Component
|
||||
if (!isLoggedIn) {
|
||||
return (
|
||||
<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-panel w-full max-w-lg border border-white relative z-10 animate-fade-in">
|
||||
|
||||
{/* Header with Logo */}
|
||||
<div className="text-center mb-10">
|
||||
<div className="group mx-auto mb-6 flex cursor-pointer justify-center">
|
||||
<YdisksBrandIcon sizeClass="w-24 h-24" logoClassName="w-full h-full text-white group-hover:scale-110 transition-transform" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">欢迎回来</h2>
|
||||
<p className="text-gray-500 font-medium">Ydisks闲鱼助手 · 自动发货与管家系统</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleLogin} className="space-y-5">
|
||||
<div className="space-y-4">
|
||||
<div className="relative group">
|
||||
<User className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="管理员账号"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value) /* 回调函数负责当前业务流程。 */}
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative group">
|
||||
<Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
||||
<input
|
||||
type="password"
|
||||
placeholder="密码"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value) /* 回调函数负责当前业务流程。 */}
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loginError && (
|
||||
<div className="p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2">
|
||||
<ShieldCheck className="w-4 h-4" /> {loginError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loginLoading}
|
||||
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70"
|
||||
>
|
||||
{loginLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : <>立即登录 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /></>}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="mt-8 pt-6 border-t border-gray-100">
|
||||
<div className="mt-6 text-center">
|
||||
<span className="text-xs text-gray-400 font-medium tracking-widest uppercase">
|
||||
Ydisks闲鱼助手 v1.0
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// handleConfigureDelivery 保存商品页传来的规则目标并切换到规则页面。
|
||||
const handleConfigureDelivery = (target /* target 表示商品页传来的规则配置目标。 */: DeliveryRuleTarget) => {
|
||||
setDeliveryRuleTarget(target);
|
||||
navigate('rules');
|
||||
};
|
||||
|
||||
// handleDeliveryTargetHandled 清理已经被规则页面消费的联动目标。
|
||||
const handleDeliveryTargetHandled = () => setDeliveryRuleTarget(undefined);
|
||||
|
||||
// handleToggleSidebar 切换侧边栏状态并持久化用户偏好。
|
||||
const handleToggleSidebar = () => setSidebarCollapsed(/* current 表示更新前的侧边栏折叠状态。 */ current => {
|
||||
// next 表示切换后的侧边栏折叠状态。
|
||||
const next = !current;
|
||||
writeSidebarCollapsed(next);
|
||||
return next;
|
||||
});
|
||||
|
||||
return (
|
||||
<AuthenticatedShell
|
||||
activeTab={activeTab}
|
||||
isAdmin={isAdmin}
|
||||
collapsed={sidebarCollapsed}
|
||||
deliveryRuleTarget={deliveryRuleTarget}
|
||||
onToggleCollapsed={handleToggleSidebar}
|
||||
onNavigate={navigate}
|
||||
onLogout={handleLogout}
|
||||
onConfigureDelivery={handleConfigureDelivery}
|
||||
onDeliveryTargetHandled={handleDeliveryTargetHandled}
|
||||
/>
|
||||
);
|
||||
}; /* AppView 表示认证页面和应用壳视图。 */
|
||||
|
||||
// App 在根部装配 SessionProvider,确保所有认证状态共享同一生命周期。
|
||||
/** App 只装配全局 Provider、错误边界和路由,不保留任何领域页面或请求状态。 */
|
||||
const App: React.FC = () => (
|
||||
<SessionProvider>
|
||||
<AppView />
|
||||
</SessionProvider>
|
||||
<AppErrorBoundary>
|
||||
<SessionProvider>
|
||||
<AppRouter />
|
||||
</SessionProvider>
|
||||
</AppErrorBoundary>
|
||||
);
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,49 @@
|
||||
import React from 'react';
|
||||
|
||||
/** ErrorBoundaryProps 描述顶层错误边界可恢复的页面子树。 */
|
||||
interface ErrorBoundaryProps {
|
||||
/** children 是由错误边界保护的整个应用路由树。 */
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/** ErrorBoundaryState 只记录渲染期故障,避免把错误对象或敏感响应写入浏览器状态。 */
|
||||
interface ErrorBoundaryState {
|
||||
/** hasError 表示应用子树是否因渲染错误而被隔离。 */
|
||||
hasError: boolean;
|
||||
}
|
||||
|
||||
/** AppErrorBoundary 隔离未捕获的页面渲染错误,并提供不依赖网络请求的恢复入口。 */
|
||||
export class AppErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
||||
/** state 保存当前子树的错误隔离状态。 */
|
||||
public state: ErrorBoundaryState = { hasError: false };
|
||||
|
||||
/** getDerivedStateFromError 在 React 捕获到子树异常时切换到静态恢复视图。 */
|
||||
public static getDerivedStateFromError(): ErrorBoundaryState {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
/** handleReload 由用户点击触发,使用完整刷新重新建立会话和路由运行环境。 */
|
||||
private handleReload = (): void => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
/** render 在正常路径渲染应用子树;捕获异常后只暴露安全的恢复界面。 */
|
||||
public render(): React.ReactNode {
|
||||
// hasError 表示当前是否需要显示错误隔离界面。
|
||||
const { hasError } = this.state;
|
||||
// children 是未发生渲染错误时应继续展示的应用路由树。
|
||||
const { children } = this.props;
|
||||
if (!hasError) return children;
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-canvas p-6 text-ink">
|
||||
<section className="max-w-md text-center">
|
||||
<h1 className="text-xl font-semibold">页面暂时无法显示</h1>
|
||||
<button className="ios-btn-primary mt-6 px-4 py-2" type="button" onClick={this.handleReload}>
|
||||
重新加载
|
||||
</button>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
/** AccountAutomation feature 使用的账号任务 API。 */
|
||||
export { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from '../../../services/api';
|
||||
@@ -0,0 +1,11 @@
|
||||
import { get, post, put, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import type { AccountTaskSettings, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope } from '../../../shared/api-contract';
|
||||
|
||||
/** 获取指定账号的自动评价与自动擦亮设置。 */
|
||||
export const getAccountTaskSettings = async (accountID: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> => get(`/api/v1/account-tasks/${accountID}`, undefined, options);
|
||||
|
||||
/** 保存指定账号的自动评价与自动擦亮设置。 */
|
||||
export const updateAccountTaskSettings = async (accountID: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> => put(`/api/v1/account-tasks/${accountID}`, settings, options);
|
||||
|
||||
/** 立即发起账号级计划任务,并使用较长超时覆盖平台执行窗口。 */
|
||||
export const runAccountTask = async (accountID: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise<AccountTaskRunResponseEnvelope> => post(`/api/v1/account-tasks/${accountID}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options });
|
||||
+4
-4
@@ -1,11 +1,11 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, AccountTaskSettingsResponse } from '../../../types';
|
||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api';
|
||||
import { useAccountAutomation } from './hooks';
|
||||
import type { AccountDetail, AccountTaskSettingsResponse } from '../../../shared/api-contract';
|
||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi';
|
||||
import { useAccountAutomation } from './accountAutomationHooks';
|
||||
|
||||
vi.mock('./api', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({
|
||||
vi.mock('./accountAutomationApi', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({
|
||||
getAccountTaskSettings: vi.fn(),
|
||||
runAccountTask: vi.fn(),
|
||||
updateAccountTaskSettings: vi.fn(),
|
||||
+4
-4
@@ -1,8 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { AccountTaskSettings, AccountTaskSummary } from '../../../types';
|
||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api';
|
||||
import { accountTaskErrorMessage, buildAccountTaskDefaults, canStartAccountTask, isAccountTaskAbortError, isCurrentAccountTaskRequest } from './state';
|
||||
import type { AccountAutomationOptions, AccountAutomationState, AccountTaskType } from './types';
|
||||
import type { AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract';
|
||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi';
|
||||
import { accountTaskErrorMessage, buildAccountTaskDefaults, canStartAccountTask, isAccountTaskAbortError, isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||
import type { AccountAutomationOptions, AccountAutomationState, AccountTaskType } from './accountAutomationTypes';
|
||||
|
||||
/** AccountAutomation Hook 的完整返回值。 */
|
||||
export type UseAccountAutomationResult = AccountAutomationState & {
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import { buildAccountTaskDefaults, canStartAccountTask, isCurrentAccountTaskRequest } from './state';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { buildAccountTaskDefaults, canStartAccountTask, isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||
|
||||
// accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。
|
||||
const accountFixture: AccountDetail = {
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import type { AccountDetail, AccountTaskSettings } from '../../../types';
|
||||
import type { AccountTaskType } from './types';
|
||||
import type { AccountDetail, AccountTaskSettings } from '../../../shared/api-contract';
|
||||
import type { AccountTaskType } from './accountAutomationTypes';
|
||||
|
||||
/** 根据账号详情创建任务设置初始草稿。 */
|
||||
export const buildAccountTaskDefaults = (account: AccountDetail): AccountTaskSettings => ({
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import type { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../../../types';
|
||||
import type { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract';
|
||||
|
||||
/** 账号任务类型。 */
|
||||
export type AccountTaskType = 'auto_rate' | 'auto_polish';
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,31 +1,325 @@
|
||||
// 账号 feature 只通过本适配层访问账号相关网络接口,页面不再直接依赖共享 API 文件。
|
||||
export {
|
||||
cancelPasswordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
checkQRLoginStatus,
|
||||
completeQRVerification,
|
||||
deleteAccount,
|
||||
generateQRLogin,
|
||||
getAccountAISettings,
|
||||
getAccountBindings,
|
||||
getAccountDetails,
|
||||
getAccountRuntimeStatuses,
|
||||
getAllAISettings,
|
||||
getLongLoginSettings,
|
||||
getNotificationChannels,
|
||||
passwordLogin,
|
||||
refreshAccountProfile,
|
||||
setLongLoginSettings,
|
||||
updateAccountAISettings,
|
||||
updateAccountPauseDuration,
|
||||
updateAccountSettings,
|
||||
updateAccountStatus,
|
||||
} from '../../../services/api';
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
// Accounts
|
||||
// addAccount 新增账号。
|
||||
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
|
||||
return post('/api/v1/accounts', { id, value, login_method: loginMethod });
|
||||
};
|
||||
|
||||
// 账号 feature 重新导出接口返回类型,保持页面与网络契约的依赖方向稳定。
|
||||
export type {
|
||||
AccountRuntimeStatus,
|
||||
LongLoginSettings,
|
||||
PasswordLoginStartResponse,
|
||||
PasswordLoginStatusResponse,
|
||||
} from '../../../services/api';
|
||||
// accountAvatarURL 生成账号头像地址。
|
||||
const accountAvatarURL = (item: AccountSummaryResponse, version: string): string => {
|
||||
// raw 原始值,用于当前 API 处理流程。
|
||||
const raw = item.avatar_url || '';
|
||||
if (!raw) return '';
|
||||
|
||||
try {
|
||||
// url 解析后的地址,用于当前 API 处理流程。
|
||||
const url = new URL(raw, window.location.origin);
|
||||
if (url.hostname.endsWith('alicdn.com')) {
|
||||
url.searchParams.set('_v', version);
|
||||
}
|
||||
return url.toString();
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
|
||||
// getAccountDetails 读取账号详情。
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => {
|
||||
// data 数据,用于当前 API 处理流程。
|
||||
const response = await get<unknown>('/api/v1/accounts/details', undefined, options);
|
||||
// data 是兼容数组、null 和历史 data 包裹后的账号摘要列表。
|
||||
const data = collectionFrom<AccountSummaryResponse>(response, ['data', 'accounts', 'details']);
|
||||
// avatarVersion 头像缓存版本,用于当前 API 处理流程。
|
||||
const avatarVersion = Date.now().toString();
|
||||
return data.map(/* 当前回调用于处理集合元素或接口响应。 */ item => ({
|
||||
id: item.id,
|
||||
cookie_configured: item.has_cookie === true,
|
||||
enabled: item.enabled,
|
||||
auto_confirm: item.auto_confirm,
|
||||
remark: item.remark,
|
||||
pause_duration: item.pause_duration,
|
||||
paused_until: Number(item.paused_until || 0),
|
||||
paused: item.paused === true,
|
||||
username: item.username || '',
|
||||
login_password_configured: undefined,
|
||||
show_browser: item.show_browser === true || item.show_browser === 1 || item.show_browser === '1' || item.show_browser === 'true',
|
||||
nickname: item.nickname || item.remark || `账号 ${item.id.substring(0,6)}`,
|
||||
avatar_url: accountAvatarURL(item, avatarVersion),
|
||||
profile_error: item.profile_error || '',
|
||||
ai_enabled: false,
|
||||
auto_rate_enabled: item.auto_rate_enabled,
|
||||
rate_content: item.rate_content || '不错的买家,交易愉快',
|
||||
auto_polish_enabled: item.auto_polish_enabled,
|
||||
polish_time: item.polish_time || '03:00',
|
||||
last_rate_scan_at: Number(item.last_rate_scan_at || 0),
|
||||
last_polish_date: item.last_polish_date || '',
|
||||
last_polish_at: Number(item.last_polish_at || 0),
|
||||
}));
|
||||
};
|
||||
|
||||
// getAccountTaskSettings 读取账号计划任务设置。
|
||||
export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
|
||||
get(`/api/v1/account-tasks/${id}`, undefined, options);
|
||||
|
||||
// updateAccountTaskSettings 更新账号计划任务设置。
|
||||
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
|
||||
put(`/api/v1/account-tasks/${id}`, settings, options);
|
||||
|
||||
// runAccountTask 立即执行账号计划任务。
|
||||
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise<AccountTaskRunResponseEnvelope> =>
|
||||
post(`/api/v1/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options });
|
||||
|
||||
|
||||
export interface AccountRuntimeStatus {
|
||||
/** state 表示状态。 */ state: NonNullable<AccountDetail['runtime_state']>;
|
||||
/** message 表示消息数据。 */ message?: string;
|
||||
/** connected 表示连接状态。 */ connected: boolean;
|
||||
/** failures 表示失败次数。 */ failures: number;
|
||||
/** updated_at 表示最后更新时间。 */ updated_at: string;
|
||||
}
|
||||
|
||||
// getAccountRuntimeStatuses 读取账号运行状态。
|
||||
export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise<Record<string, AccountRuntimeStatus>> => {
|
||||
const response = await get<unknown>('/api/v1/accounts/runtime-status', undefined, options);
|
||||
// statuses 是兼容直接映射、statuses 包裹和 null 的运行状态索引。
|
||||
const statuses = objectFrom<Record<string, AccountRuntimeStatus>>(response, ['statuses', 'data', 'result']);
|
||||
return statuses || {};
|
||||
};
|
||||
|
||||
// generateQRLogin 生成二维码登录会话。
|
||||
export const generateQRLogin = async (options?: RequestControlOptions): Promise<QRLoginGenerateResponse> => {
|
||||
// 风控后匿名 token 接口可能超过通用的 30 秒请求窗口;后端总生成窗口为 2 分钟。
|
||||
return post('/api/v1/qr-login/generate', undefined, { ...options, timeoutMs: options?.timeoutMs ?? 130_000 });
|
||||
};
|
||||
|
||||
// checkQRLoginStatus 查询二维码登录状态。
|
||||
export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<QRLoginStatusResponse> => {
|
||||
return get(`/api/v1/qr-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
|
||||
};
|
||||
|
||||
// completeQRVerification 完成二维码登录验证。
|
||||
export const completeQRVerification = async (
|
||||
sessionId: string,
|
||||
targetAccountId?: string,
|
||||
): Promise<QRLoginVerificationResponse> => {
|
||||
return post(`/api/v1/qr-login/complete-verification/${sessionId}`, {
|
||||
target_account_id: targetAccountId || '',
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// updateAccountStatus 更新账号状态。
|
||||
export const updateAccountStatus = async (id: string, enabled: boolean): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/status`, { enabled });
|
||||
};
|
||||
|
||||
// deleteAccount 删除账号。
|
||||
export const deleteAccount = async (id: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/accounts/${id}`);
|
||||
};
|
||||
|
||||
// updateAccountRemark 更新账号备注。
|
||||
export const updateAccountRemark = async (id: string, remark: string): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/remark`, { remark });
|
||||
};
|
||||
|
||||
// updateAccountAutoConfirm 更新账号自动确认设置。
|
||||
export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm });
|
||||
};
|
||||
|
||||
// updateAccountPauseDuration 更新账号暂停时长。
|
||||
export const updateAccountPauseDuration = async (id: string, pauseDuration: number, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration }, options);
|
||||
};
|
||||
|
||||
// updateAccountCookie 更新账号登录凭证。
|
||||
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}`, { id, value, login_method: loginMethod });
|
||||
};
|
||||
|
||||
export interface AccountSettingsUpdate {
|
||||
/** cookie 表示登录凭证。 */ cookie?: string;
|
||||
/** remark 表示备注。 */ remark?: string;
|
||||
/** auto_confirm 表示自动确认状态。 */ auto_confirm?: boolean;
|
||||
/** pause_duration 表示暂停时长。 */ pause_duration?: number;
|
||||
/** username 表示用户名。 */ username?: string;
|
||||
/** login_password 表示登录密码。 */ login_password?: string;
|
||||
/** clear_password 表示是否清理登录密码。 */ clear_password?: boolean;
|
||||
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
|
||||
/** channel_ids 表示通知渠道标识列表。 */ channel_ids?: number[];
|
||||
}
|
||||
|
||||
// updateAccountSettings 更新账号设置。
|
||||
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/settings`, data, options);
|
||||
};
|
||||
|
||||
export interface LongLoginSettings {
|
||||
/** can_open_long_login 表示是否允许开启长期登录。 */ can_open_long_login: boolean;
|
||||
/** enabled 表示启用状态。 */ enabled: boolean;
|
||||
}
|
||||
|
||||
// getLongLoginSettings 读取长期登录设置。
|
||||
export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise<LongLoginSettings> => {
|
||||
return get(`/api/v1/accounts/${id}/long-login`, undefined, options);
|
||||
};
|
||||
|
||||
// setLongLoginSettings 设置长期登录开关。
|
||||
export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise<LongLoginSettings> => {
|
||||
return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options);
|
||||
};
|
||||
|
||||
export interface PasswordLoginStartResponse {
|
||||
/** success 表示是否成功。 */ success: boolean;
|
||||
/** session_id 表示会话标识。 */ session_id?: string;
|
||||
/** status 表示状态值。 */ status?: 'processing' | 'failed';
|
||||
/** message 表示消息数据。 */ message?: string;
|
||||
}
|
||||
|
||||
export interface PasswordLoginStatusResponse {
|
||||
/** status 表示状态值。 */ status: 'processing' | 'success' | 'failed' | 'verification_required' | 'not_found' | 'error';
|
||||
/** message 表示消息数据。 */ message?: string;
|
||||
/** account_id 表示账号标识。 */ account_id?: string;
|
||||
/** is_new_account 表示是否为新账号。 */ is_new_account?: boolean;
|
||||
/** cookie_count 表示登录凭证数量。 */ cookie_count?: number;
|
||||
/** verification_url 表示验证地址。 */ verification_url?: string;
|
||||
/** screenshot_path 表示验证截图路径。 */ screenshot_path?: string;
|
||||
/** qr_code_url 表示二维码地址。 */ qr_code_url?: string;
|
||||
/** error 表示错误信息。 */ error?: string;
|
||||
/** reason 表示失败原因。 */ reason?: string;
|
||||
}
|
||||
|
||||
// passwordLogin 执行密码登录。
|
||||
export const passwordLogin = async (data: {
|
||||
/** account_id 表示账号标识。 */ account_id: string;
|
||||
/** account 表示账号。 */ account: string;
|
||||
/** password 表示密码。 */ password: string;
|
||||
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
|
||||
}, options?: RequestControlOptions): Promise<PasswordLoginStartResponse> => {
|
||||
return post('/api/v1/password-login', data, options);
|
||||
};
|
||||
|
||||
// checkPasswordLoginStatus 查询密码登录状态。
|
||||
export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<PasswordLoginStatusResponse> => {
|
||||
return get(`/api/v1/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
|
||||
};
|
||||
|
||||
// cancelPasswordLogin 取消密码登录。
|
||||
export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options);
|
||||
};
|
||||
|
||||
// refreshAccountProfile 刷新账号资料。
|
||||
export const refreshAccountProfile = async (id: string): Promise<CookieProfileResponse> => {
|
||||
return post(`/api/v1/accounts/${id}/refresh-profile`, {});
|
||||
};
|
||||
|
||||
// updateAccountLoginInfo 更新账号登录信息。
|
||||
export const updateAccountLoginInfo = async (id: string, data: {
|
||||
/** username 表示用户名。 */ username?: string;
|
||||
/** login_password 表示登录密码。 */ login_password?: string;
|
||||
/** clear_password 表示是否清理登录密码。 */ clear_password?: boolean;
|
||||
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
|
||||
}): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/login-info`, data);
|
||||
};
|
||||
|
||||
// getAllAISettings 读取全部人工智能设置。
|
||||
export const getAllAISettings = async (options?: RequestControlOptions): Promise<Record<string, AIReplySettings>> => {
|
||||
const response = await get<unknown>('/api/v1/settings/ai-reply', undefined, options);
|
||||
// settings 是兼容直接映射、data 包裹和 null 的账号 AI 设置索引。
|
||||
return objectFrom<Record<string, AIReplySettings>>(response, ['settings', 'data', 'result']) || {};
|
||||
};
|
||||
|
||||
|
||||
// getAccountAISettings 读取账号人工智能设置。
|
||||
export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise<AIReplySettingsResponse> => {
|
||||
return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options);
|
||||
}
|
||||
|
||||
// updateAccountAISettings 更新账号人工智能设置。
|
||||
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||
// payload 请求载荷,用于当前 API 处理流程。
|
||||
const payload = {
|
||||
ai_enabled: settings.ai_enabled ?? false,
|
||||
max_discount_percent: settings.max_discount_percent ?? 10,
|
||||
max_discount_amount: settings.max_discount_amount ?? 100,
|
||||
max_bargain_rounds: settings.max_bargain_rounds ?? 3,
|
||||
custom_prompts: settings.custom_prompts ?? ''
|
||||
};
|
||||
return put(`/api/v1/settings/ai-reply/${cookieId}`, payload, options);
|
||||
}
|
||||
|
||||
|
||||
// parseNotificationEventTypes 解析通知事件类型。
|
||||
const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
|
||||
if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return [];
|
||||
try {
|
||||
// parsed 转换后的数值,用于当前 API 处理流程。
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[];
|
||||
} catch {
|
||||
// fall back to legacy comma/semicolon separated values
|
||||
}
|
||||
return raw.split(/[,\s;]+/).map(/* 当前回调用于处理集合元素或接口响应。 */ v => v.trim()).filter(Boolean) as NotificationEventType[];
|
||||
};
|
||||
|
||||
// stringifyNotificationEventTypes 序列化通知事件类型。
|
||||
const stringifyNotificationEventTypes = (events?: NotificationEventType[]): string => {
|
||||
// clean 清理后的事件类型列表,用于当前 API 处理流程。
|
||||
const clean = Array.from(new Set((events || []).filter(Boolean)));
|
||||
return clean.length > 0 ? JSON.stringify(clean) : '';
|
||||
};
|
||||
|
||||
// getNotificationChannels 读取通知渠道。
|
||||
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: NotificationChannel[] }> => {
|
||||
// result 接口响应结果,用于当前 API 处理流程。
|
||||
const result = await get<unknown>('/api/v1/notifications/channels', undefined, options);
|
||||
// channels 通知渠道列表,用于当前 API 处理流程。
|
||||
const channels = collectionFrom<NotificationChannelResponse>(result, ['data', 'channels', 'items']).map(/* 当前回调用于处理集合元素或接口响应。 */ (item: NotificationChannelResponse) => {
|
||||
// parsedConfig 解析后的通知配置,用于当前 API 处理流程。
|
||||
let parsedConfig;
|
||||
try {
|
||||
parsedConfig = typeof item.config === 'string' ? JSON.parse(item.config) : item.config;
|
||||
} catch {
|
||||
parsedConfig = {};
|
||||
}
|
||||
// normalizedType 是兼容旧渠道别名后的前端渠道类型。
|
||||
const normalizedType = (item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type)) as NotificationChannel['type'];
|
||||
return {
|
||||
id: String(item.id),
|
||||
name: item.name,
|
||||
type: normalizedType,
|
||||
config: parsedConfig,
|
||||
event_types: parseNotificationEventTypes(item.event_types),
|
||||
enabled: item.enabled,
|
||||
created_at: item.created_at,
|
||||
updated_at: item.updated_at,
|
||||
};
|
||||
});
|
||||
return { success: true, data: channels };
|
||||
}
|
||||
|
||||
|
||||
// 账号 ↔ 渠道 绑定(覆盖式)
|
||||
export const getAccountBindings = async (cookieId: string, options?: RequestControlOptions): Promise<number[]> => {
|
||||
// response 是兼容直接绑定对象、data 包裹和 null 的通知绑定响应。
|
||||
const response = await get<unknown>(`/api/v1/notifications/accounts/${cookieId}/bindings`, undefined, options);
|
||||
// result 是去除历史包裹后的账号通知绑定对象。
|
||||
const result = objectFrom<Partial<AccountBindingsResponse>>(response, ['data', 'result']) || {};
|
||||
return Array.isArray(result.channel_ids) ? result.channel_ids : [];
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Bot, Loader2, Save, Settings, X } from 'lucide-react';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../../types';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract';
|
||||
|
||||
// AccountAISettingsModalProps 描述账号 AI 设置弹窗需要的状态和回调。
|
||||
export interface AccountAISettingsModalProps {
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { CalendarClock, Loader2, MessageSquareQuote, Play, Save, Sparkles, X } from 'lucide-react';
|
||||
import { AccountDetail, AccountTaskSettings } from '../types';
|
||||
import { useAccountAutomation } from '../app/features/accountAutomation/hooks';
|
||||
import { AccountDetail, AccountTaskSettings } from '../../../../shared/api-contract';
|
||||
import { useAccountAutomation } from '../accountAutomationHooks';
|
||||
|
||||
interface Props {
|
||||
/** account 表示账号。 */ account: AccountDetail;
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { AlertCircle, Bot, CalendarClock, Check, Clock, Loader2, MessageCircle, Power, QrCode, RefreshCw, Sparkles, Trash2, User, Edit2 } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../types';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
import { accountRuntimePresentation } from '../runtime';
|
||||
|
||||
// AccountCardProps 描述账号卡片展示所需的数据和动作。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { AlertCircle, Loader2, Trash2, X } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../types';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
|
||||
// AccountDeleteDialogProps 描述账号删除确认框需要的状态和回调。
|
||||
export interface AccountDeleteDialogProps {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Bell, Check, Clock, Eye, EyeOff, Key, Loader2, X } from 'lucide-react';
|
||||
import { SquareQRCode } from '../../../../components/SquareQRCode';
|
||||
import type { NotificationChannel } from '../../../../types';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
import type { NotificationChannel } from '../../../../shared/api-contract';
|
||||
import type { AccountEditForm, AccountEditModalProps } from '../types';
|
||||
|
||||
// AccountEditModal 负责账号备注、暂停、登录信息和通知绑定的编辑界面。
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Check, Loader2, X } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../types';
|
||||
import { RiskVerificationPanel } from '../../../../components/RiskVerificationPanel';
|
||||
import { SquareQRCode } from '../../../../components/SquareQRCode';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
|
||||
// AccountQRCodeModalProps 描述二维码登录弹窗的展示状态和关闭回调。
|
||||
export interface AccountQRCodeModalProps {
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { fireEvent, render, screen, cleanup } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../../types';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract';
|
||||
import { AccountAISettingsModal } from './AccountAISettingsModal';
|
||||
import { AccountCard } from './AccountCard';
|
||||
import { AccountDeleteDialog } from './AccountDeleteDialog';
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { act } from 'react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api';
|
||||
import { useAccountsData } from './hooks';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api';
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { mergeAccountRuntimeStatuses } from './runtime';
|
||||
import type { AccountAISettingsState } from './types';
|
||||
|
||||
|
||||
+10
-10
@@ -2,7 +2,7 @@
|
||||
import React from 'react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail } from '../types';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
|
||||
// accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。
|
||||
const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({
|
||||
@@ -26,7 +26,7 @@ const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试
|
||||
pollCallbacks: null as Record<string, (...args: any[]) => void> | null,
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/accounts/hooks', /* accountsHookMockFactory 提供账号列表数据 Hook 替身。 */ () => ({
|
||||
vi.mock('../hooks', /* accountsHookMockFactory 提供账号列表数据 Hook 替身。 */ () => ({
|
||||
useAccountsData: /* useAccountsDataMock 返回固定账号列表和刷新操作。 */ () => ({
|
||||
accounts: accountListMocks.accounts,
|
||||
setAccounts: accountListMocks.setAccounts,
|
||||
@@ -35,7 +35,7 @@ vi.mock('../app/features/accounts/hooks', /* accountsHookMockFactory 提供账
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/accounts/submoduleHooks', /* submoduleHookMockFactory 提供账号弹窗状态 Hook 替身。 */ () => ({
|
||||
vi.mock('../submoduleHooks', /* submoduleHookMockFactory 提供账号弹窗状态 Hook 替身。 */ () => ({
|
||||
useAccountSubmodules: /* useAccountSubmodulesMock 返回不阻断页面渲染的子模块状态。 */ () => ({
|
||||
longLogin: false,
|
||||
notifChannels: [],
|
||||
@@ -63,7 +63,7 @@ vi.mock('../app/features/accounts/submoduleHooks', /* submoduleHookMockFactory
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/accounts/api', /* accountApiMockFactory 提供账号页面 API 替身。 */ () => ({
|
||||
vi.mock('../api', /* accountApiMockFactory 提供账号页面 API 替身。 */ () => ({
|
||||
updateAccountStatus: accountListMocks.updateAccountStatus,
|
||||
deleteAccount: accountListMocks.deleteAccount,
|
||||
generateQRLogin: accountListMocks.generateQRLogin,
|
||||
@@ -72,7 +72,7 @@ vi.mock('../app/features/accounts/api', /* accountApiMockFactory 提供账号页
|
||||
refreshAccountProfile: accountListMocks.refreshAccountProfile,
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/accounts/qrPolling', /* qrPollingMockFactory 提供二维码轮询器替身。 */ () => ({
|
||||
vi.mock('../qrPolling', /* qrPollingMockFactory 提供二维码轮询器替身。 */ () => ({
|
||||
createLatestRequestGate: /* requestGateFactory 创建二维码请求代次门禁。 */ () => ({
|
||||
next: accountListMocks.requestNext,
|
||||
isCurrent: accountListMocks.requestIsCurrent,
|
||||
@@ -84,7 +84,7 @@ vi.mock('../app/features/accounts/qrPolling', /* qrPollingMockFactory 提供二
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/accounts/components/AccountCard', /* accountCardMockFactory 提供账号卡片交互替身。 */ () => {
|
||||
vi.mock('../components/AccountCard', /* accountCardMockFactory 提供账号卡片交互替身。 */ () => {
|
||||
// AccountCardMock 渲染页面测试需要的账号操作入口。
|
||||
const AccountCardMock: React.FC<any> = (props /* props 表示账号卡片及其事件回调。 */) => (
|
||||
<div data-testid={`account-card-${props.account.id}`}>
|
||||
@@ -98,7 +98,7 @@ vi.mock('../app/features/accounts/components/AccountCard', /* accountCardMockFac
|
||||
return { AccountCard: AccountCardMock };
|
||||
});
|
||||
|
||||
vi.mock('../app/features/accounts/components/AccountDeleteDialog', /* deleteDialogMockFactory 提供删除确认弹窗替身。 */ () => {
|
||||
vi.mock('../components/AccountDeleteDialog', /* deleteDialogMockFactory 提供删除确认弹窗替身。 */ () => {
|
||||
// AccountDeleteDialogMock 展示删除错误并暴露确认/关闭操作。
|
||||
const AccountDeleteDialogMock: React.FC<any> = (props /* props 表示删除弹窗及其操作回调。 */) => (
|
||||
<div data-testid="delete-dialog">
|
||||
@@ -110,7 +110,7 @@ vi.mock('../app/features/accounts/components/AccountDeleteDialog', /* deleteDial
|
||||
return { AccountDeleteDialog: AccountDeleteDialogMock };
|
||||
});
|
||||
|
||||
vi.mock('../app/features/accounts/components/AccountQRCodeModal', /* qrModalMockFactory 提供二维码弹窗替身。 */ () => {
|
||||
vi.mock('../components/AccountQRCodeModal', /* qrModalMockFactory 提供二维码弹窗替身。 */ () => {
|
||||
// AccountQRCodeModalMock 展示二维码状态并暴露关闭操作。
|
||||
const AccountQRCodeModalMock: React.FC<any> = (props /* props 表示二维码弹窗及其操作回调。 */) => (
|
||||
<div data-testid="qr-modal">
|
||||
@@ -121,11 +121,11 @@ vi.mock('../app/features/accounts/components/AccountQRCodeModal', /* qrModalMock
|
||||
return { AccountQRCodeModal: AccountQRCodeModalMock };
|
||||
});
|
||||
|
||||
vi.mock('../app/features/accounts/components/AccountEditModal', /* editModalMockFactory 提供账号编辑弹窗替身。 */ () => ({
|
||||
vi.mock('../components/AccountEditModal', /* editModalMockFactory 提供账号编辑弹窗替身。 */ () => ({
|
||||
AccountEditModal: /* AccountEditModalMock 表示账号编辑弹窗替身。 */ () => null,
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/accounts/components/AccountAISettingsModal', /* aiModalMockFactory 提供 AI 设置弹窗替身。 */ () => ({
|
||||
vi.mock('../components/AccountAISettingsModal', /* aiModalMockFactory 提供 AI 设置弹窗替身。 */ () => ({
|
||||
AccountAISettingsModal: /* AccountAISettingsModalMock 表示 AI 设置弹窗替身。 */ () => null,
|
||||
}));
|
||||
|
||||
+12
-12
@@ -1,22 +1,22 @@
|
||||
import React, { useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { AccountDetail } from '../types';
|
||||
import { AccountDetail } from '../../../../shared/api-contract';
|
||||
import {
|
||||
updateAccountStatus,
|
||||
deleteAccount,
|
||||
refreshAccountProfile,
|
||||
} from '../app/features/accounts/api';
|
||||
} from '../api';
|
||||
import { Loader2, QrCode, User } from 'lucide-react';
|
||||
import AccountAutomationModal from './AccountAutomationModal';
|
||||
import { AccountEditModal } from '../app/features/accounts/components/AccountEditModal';
|
||||
import { AccountAISettingsModal } from '../app/features/accounts/components/AccountAISettingsModal';
|
||||
import { AccountCard } from '../app/features/accounts/components/AccountCard';
|
||||
import { AccountDeleteDialog } from '../app/features/accounts/components/AccountDeleteDialog';
|
||||
import { AccountQRCodeModal } from '../app/features/accounts/components/AccountQRCodeModal';
|
||||
import { useAccountsData } from '../app/features/accounts/hooks';
|
||||
import { useAccountQRCodeLogin } from '../app/features/accounts/qrLogin';
|
||||
import { useAccountSubmodules, type AccountModalType } from '../app/features/accounts/submoduleHooks';
|
||||
import type { AccountEditForm } from '../app/features/accounts/types';
|
||||
import AccountAutomationModal from '../components/AccountAutomationModal';
|
||||
import { AccountEditModal } from '../components/AccountEditModal';
|
||||
import { AccountAISettingsModal } from '../components/AccountAISettingsModal';
|
||||
import { AccountCard } from '../components/AccountCard';
|
||||
import { AccountDeleteDialog } from '../components/AccountDeleteDialog';
|
||||
import { AccountQRCodeModal } from '../components/AccountQRCodeModal';
|
||||
import { useAccountsData } from '../hooks';
|
||||
import { useAccountQRCodeLogin } from '../qrLogin';
|
||||
import { useAccountSubmodules, type AccountModalType } from '../submoduleHooks';
|
||||
import type { AccountEditForm } from '../types';
|
||||
|
||||
// AccountList 渲染账号列表组件。
|
||||
const AccountList: React.FC = () => {
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
|
||||
// qrLoginMocks 保存二维码登录协调器测试使用的接口替身。
|
||||
const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { checkQRLoginStatus, completeQRVerification, generateQRLogin } from './api';
|
||||
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
|
||||
|
||||
|
||||
File renamed without changes.
@@ -1,11 +1,10 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { accountRuntimePresentation, isOlderStatus, mergeAccountRuntimeStatuses } from './runtime';
|
||||
|
||||
// account 创建运行状态测试使用的最小账号对象。
|
||||
const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
|
||||
id: 'account-1',
|
||||
value: 'cookie',
|
||||
enabled: true,
|
||||
auto_confirm: false,
|
||||
...overrides,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AccountRuntimeStatus } from './api';
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import type { AccountRuntimePresentation } from './types';
|
||||
|
||||
// isOlderStatus 判断传入的运行时快照是否早于账号当前已展示的快照。
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import {
|
||||
buildAccountLoginInfoUpdate,
|
||||
isCurrentAccountRequest,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AccountDetail } from '../../../types';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import type { PasswordLoginStatusResponse } from './api';
|
||||
import type { AccountEditForm, PasswordLoginView } from './types';
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../types';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../shared/api-contract';
|
||||
import {
|
||||
cancelPasswordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
@@ -101,6 +101,7 @@ describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知
|
||||
expect(hook.result.current.longLogin.canOpen).toBe(true);
|
||||
expect(hook.result.current.notifChannels).toHaveLength(1);
|
||||
expect(hook.result.current.selectedChannelIds).toEqual([1]);
|
||||
expect(setEditForm).toHaveBeenCalledWith(expect.objectContaining({ cookie: '', login_password: '' }));
|
||||
await act(
|
||||
// toggleAction 切换通知渠道绑定。
|
||||
() => hook.result.current.toggleNotificationChannel(2),
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../types';
|
||||
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract';
|
||||
import { cancelPasswordLogin, checkPasswordLoginStatus, getAccountAISettings, getAccountBindings, getLongLoginSettings, getNotificationChannels, passwordLogin, setLongLoginSettings, updateAccountAISettings, updateAccountPauseDuration, updateAccountSettings } from './api';
|
||||
import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, passwordLoginViewFromStatus, shouldUpdateAccountPause } from './state';
|
||||
import type { AccountEditForm, LongLoginState, PasswordLoginView } from './types';
|
||||
import { shouldSaveNotificationBindings } from '../../../components/accountBindings';
|
||||
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||
|
||||
/** AccountList 当前编辑弹窗类型。 */
|
||||
export type AccountModalType = 'edit' | 'ai-settings' | null;
|
||||
@@ -124,7 +124,8 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
clearPasswordTimer();
|
||||
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
setEditingAccount(account);
|
||||
setEditForm({ remark: account.remark || '', cookie: account.value || '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: account.login_password || '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false });
|
||||
// 摘要接口不会返回 Cookie 或密码明文;编辑表单只接收本次用户主动输入的秘密。
|
||||
setEditForm({ remark: account.remark || '', cookie: '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false });
|
||||
setActiveModal('edit');
|
||||
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
// longLoginResult 保存长登录设置读取结果。
|
||||
@@ -200,7 +201,8 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
// payload 保存需要提交的账号编辑补丁。
|
||||
const payload: Parameters<typeof updateAccountSettings>[1] = {};
|
||||
if (editForm.remark !== (editingAccount.remark || '')) payload.remark = editForm.remark;
|
||||
if (editForm.cookie && editForm.cookie !== (editingAccount.value || '')) payload.cookie = editForm.cookie;
|
||||
// 编辑表单中的 Cookie 只有用户本次输入时才会提交,避免从账号摘要读取或回填明文。
|
||||
if (editForm.cookie) payload.cookie = editForm.cookie;
|
||||
if (editForm.auto_confirm !== editingAccount.auto_confirm) payload.auto_confirm = editForm.auto_confirm;
|
||||
if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) payload.pause_duration = editForm.pause_duration;
|
||||
// loginInfo 保存登录字段变更补丁。
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../types';
|
||||
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract';
|
||||
|
||||
// AccountEditForm 描述账号编辑弹窗中的可编辑字段。
|
||||
export interface AccountEditForm {
|
||||
|
||||
@@ -2,45 +2,27 @@ import { afterEach, expect, test, vi } from 'vitest';
|
||||
import {
|
||||
addAccount,
|
||||
cancelPasswordLogin,
|
||||
deleteItemPublishBatch, deleteItem, cancelItemPublishBatch, retryFailedItemPublishBatch,
|
||||
checkPasswordLoginStatus,
|
||||
checkQRLoginStatus, completeQRVerification, generateQRLogin,
|
||||
createNotificationChannel, getAllAISettings, getAccountAISettings, updateAccountAISettings, fetchAIModels,
|
||||
getAccountDetails, getAccountRuntimeStatuses, updateAccountStatus,
|
||||
getAutomationIssues, changePassword, createItem, deleteAccount, deleteOrder, deleteShippingRule, updateLoginCredentials,
|
||||
getItems, getItemDetail, syncItemsFromAccount,
|
||||
getItemPublishBatches, getItemPublishBatch, startItemPublishBatch,
|
||||
getNotificationChannels, getMessageNotifications, getAccountBindings,
|
||||
getOrders, getOrderDetail, updateOrder,
|
||||
getAdminStats, getDashboardStats, getOrderAnalytics,
|
||||
getReplyRules, getDefaultReplies, getDefaultReply, updateDefaultReply, deleteDefaultReply, clearDefaultReplyRecords,
|
||||
getShippingRules,
|
||||
getShippingRulesPage,
|
||||
getSystemSettings, getHealth, getCards, createCard, updateCard, deleteCard, getCardDetails, batchCreateCards, appendCardData,
|
||||
getValidOrders,
|
||||
publishItem, recommendPublishCategory, previewItemPublishBatch,
|
||||
logout,
|
||||
importOrders,
|
||||
getAllAISettings, getAccountAISettings, updateAccountAISettings,
|
||||
getAccountDetails, getAccountRuntimeStatuses, updateAccountStatus, deleteAccount,
|
||||
passwordLogin,
|
||||
resolveAutomationRun,
|
||||
resolveDeferredAutomationTask,
|
||||
syncOrders, cancelOrderRefreshJob, syncSingleOrder, manualShipOrder,
|
||||
updateReplyRule,
|
||||
deleteReplyRule,
|
||||
updateAccountCookie,
|
||||
updateAccountLoginInfo,
|
||||
updateAccountSettings, updateAccountRemark, updateAccountAutoConfirm, updateAccountPauseDuration, getLongLoginSettings, setLongLoginSettings, refreshAccountProfile,
|
||||
updateItem,
|
||||
updateNotificationChannel, deleteNotificationChannel, setMessageNotification, deleteMessageNotification, deleteAccountNotifications, setAccountBindings, testNotificationChannel,
|
||||
updateSystemSettings,
|
||||
updateShippingRule,
|
||||
getChatSessions, getChatSessionPage,
|
||||
getChatMessages, getChatMessagePage,
|
||||
sendChatMessage, sendChatImage,
|
||||
markChatRead,
|
||||
getAccountTaskSettings, updateAccountTaskSettings,
|
||||
runAccountTask, login, initializeAdmin, verifySession,
|
||||
} from './api';
|
||||
runAccountTask,
|
||||
} from './accounts/api';
|
||||
import { appendCardData, batchCreateCards, createCard, deleteCard, getCardDetails, getCards, updateCard } from './cards/api';
|
||||
import { getChatMessagePage, getChatMessages, getChatSessionPage, getChatSessions, markChatRead, sendChatImage, sendChatMessage } from './chat/api';
|
||||
import { getDashboardStats, getOrderAnalytics, getValidOrders } from './dashboard/api';
|
||||
import { createItem, deleteItem, deleteItemPublishBatch, cancelItemPublishBatch, getItemDetail, getItemPublishBatch, getItemPublishBatches, getItems, previewItemPublishBatch, publishItem, recommendPublishCategory, retryFailedItemPublishBatch, startItemPublishBatch, syncItemsFromAccount, updateItem } from './items/api';
|
||||
import { createNotificationChannel, deleteAccountNotifications, deleteMessageNotification, deleteNotificationChannel, getAccountBindings, getMessageNotifications, getNotificationChannels, setAccountBindings, setMessageNotification, testNotificationChannel, updateNotificationChannel } from './notifications/api';
|
||||
import { cancelOrderRefreshJob, deleteOrder, getAdminStats, getOrderDetail, getOrders, importOrders, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './orders/api';
|
||||
import { clearDefaultReplyRecords, deleteDefaultReply, deleteReplyRule, deleteShippingRule, getAutomationIssues, getDefaultReplies, getDefaultReply, getReplyRules, getShippingRules, getShippingRulesPage, resolveAutomationRun, resolveDeferredAutomationTask, updateDefaultReply, updateReplyRule, updateShippingRule } from './rules/api';
|
||||
import { initializeAdmin, login, logout, verifySession } from './session/api';
|
||||
import { changePassword, fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings } from './settings/api';
|
||||
import { getHealth } from './system/api';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
@@ -579,12 +561,43 @@ test('getAccountDetails normalizes show_browser and never exposes password', asy
|
||||
id: 'acc1',
|
||||
username: 'login-user',
|
||||
show_browser: true,
|
||||
login_password: '',
|
||||
paused_until: 1780000000,
|
||||
paused: true,
|
||||
});
|
||||
expect(accounts[0]).not.toHaveProperty('login_password');
|
||||
expect(accounts[0]).not.toHaveProperty('value');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('列表 API 将 null 和历史 data 包裹统一为空数组', async () => {
|
||||
// fetchMock 依次模拟账号、商品、订单和规则接口的历史空响应。
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse(null))
|
||||
.mockResolvedValueOnce(jsonResponse({ data: null }))
|
||||
.mockResolvedValueOnce(jsonResponse(null))
|
||||
.mockResolvedValueOnce(jsonResponse({ data: null }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(getAccountDetails()).resolves.toEqual([]);
|
||||
await expect(getItems()).resolves.toEqual([]);
|
||||
await expect(getOrders()).resolves.toMatchObject({ data: [], total: 0 });
|
||||
await expect(getShippingRules()).resolves.toEqual([]);
|
||||
} /* 回调函数验证列表接口的空集合契约。 */);
|
||||
|
||||
test('列表 API 接受历史命名包裹对象并保持具名 UI 结果', async () => {
|
||||
// fetchMock 模拟订单、商品、卡密和批次接口各自的历史字段名称。
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ orders: [{ order_id: 'o-wrap', order_status: 'paid' }] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ items: [{ cookie_id: 'a1', item_id: 'i1', item_title: '商品' }] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ cards: [{ id: 1, name: '库存', type: 'data', enabled: true }] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ batches: [{ id: 'b1', status: 'running' }] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(getOrders()).resolves.toMatchObject({ data: [{ id: 'o-wrap', status: 'pending_ship' }] });
|
||||
await expect(getItems()).resolves.toMatchObject([{ id: 'a1-i1' }]);
|
||||
await expect(getCards()).resolves.toMatchObject([{ id: 1, name: '库存' }]);
|
||||
await expect(getItemPublishBatches()).resolves.toEqual([{ id: 'b1', status: 'running' }]);
|
||||
} /* 回调函数验证历史包裹字段的兼容归一。 */);
|
||||
|
||||
test('getAccountDetails 归一化头像地址并保留非法地址', /* 当前回调验证头像缓存参数和 URL 兼容边界。 */ async () => {
|
||||
// windowStub 是头像 URL 解析使用的浏览器位置替身。
|
||||
vi.stubGlobal('window', { location: { origin: 'http://localhost' } });
|
||||
@@ -1,12 +1,78 @@
|
||||
// 卡密 feature 只通过本适配层访问库存和批量接口,页面不直接依赖共享 API 文件。
|
||||
export {
|
||||
appendCardData,
|
||||
batchCreateCards,
|
||||
createCard,
|
||||
deleteCard,
|
||||
getCards,
|
||||
updateCard,
|
||||
} from '../../../services/api';
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
// Cards
|
||||
// normalizeCard 归一化卡密数据。
|
||||
const normalizeCard = (item: any): Card => {
|
||||
// apiConfig 卡密接口配置,用于当前 API 处理流程。
|
||||
let apiConfig = item.api_config;
|
||||
if (typeof apiConfig === 'string' && apiConfig.trim()) {
|
||||
try {
|
||||
apiConfig = JSON.parse(apiConfig);
|
||||
} catch {
|
||||
apiConfig = undefined;
|
||||
}
|
||||
}
|
||||
return {...item, api_config: apiConfig || undefined} as Card;
|
||||
};
|
||||
|
||||
// 卡密 feature 重新导出接口响应类型,保持批量结果契约稳定。
|
||||
export type { CardAppendResponse, CardBatchResponse } from '../../../types';
|
||||
// cardPayload 卡密请求载荷,用于当前 API 处理流程。
|
||||
const cardPayload = (data: Partial<Card>): Record<string, unknown> => ({
|
||||
...data,
|
||||
api_config: data.api_config ? JSON.stringify(data.api_config) : '',
|
||||
});
|
||||
|
||||
// getCards 读取卡密列表。
|
||||
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const res = await get<unknown>('/api/v1/cards', undefined, options);
|
||||
// cards 卡密列表,用于当前 API 处理流程。
|
||||
const cards = collectionFrom<Card>(res, ['cards', 'data', 'items']);
|
||||
return cards.map(normalizeCard);
|
||||
};
|
||||
|
||||
// createCard 创建卡密组。
|
||||
export const createCard = async (data: Partial<Card>): Promise<MutationIDResponse> => {
|
||||
return post('/api/v1/cards', cardPayload(data));
|
||||
};
|
||||
|
||||
// updateCard 更新卡密组。
|
||||
export const updateCard = async (cardId: string | number, data: Partial<Card>): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/cards/${cardId}`, cardPayload(data));
|
||||
};
|
||||
|
||||
// deleteCard 删除卡密组。
|
||||
export const deleteCard = async (cardId: string | number): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/cards/${cardId}`);
|
||||
};
|
||||
|
||||
// getCardDetails 读取卡密组详情。
|
||||
export const getCardDetails = async (cardId: string | number): Promise<Card> => {
|
||||
// card 卡密详情,用于当前 API 处理流程。
|
||||
const card = await get<Card>(`/api/v1/cards/${cardId}/details`);
|
||||
return normalizeCard(card);
|
||||
};
|
||||
|
||||
// 批量创建卡密组(上传表格)
|
||||
export const batchCreateCards = async (file: File, options?: RequestControlOptions): Promise<CardBatchResponse> => {
|
||||
// 批量创建接口返回总行数、成功数、失败数和逐行结果。
|
||||
// CardBatchResponse 保留旧字段名称,调用方无需转换统计字段。
|
||||
// rows 中的 id 只在创建成功时返回。
|
||||
// rows 中的 error 只在对应行失败时返回。
|
||||
// 表单上传方式和接口路径保持不变。
|
||||
// 此处只收紧 TypeScript 响应契约。
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
return postForm('/api/v1/cards/batch', body, options);
|
||||
};
|
||||
|
||||
// 往 data 类型卡密组批量追加卡密号
|
||||
export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise<CardAppendResponse> => {
|
||||
return post(`/api/v1/cards/${cardId}/append-data`, { content }, options);
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { Card } from '../../../types';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { canSubmitAppend, filterCards, isCurrentCardRequest, previewAppendContent } from './batchState';
|
||||
|
||||
// cards 是卡密筛选测试使用的最小卡密组列表。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Card } from '../../../types';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
|
||||
// filterCards 按类型和名称筛选卡密组,两个条件同时满足才保留。
|
||||
export const filterCards = (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Card } from '../../../types';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { createCard, deleteCard, updateCard } from './api';
|
||||
import { useCardActions } from './cardActions';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { Card } from '../../../types';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { createCard, deleteCard, updateCard } from './api';
|
||||
import { filterCards } from './batchState';
|
||||
import type { AddCardForm, EditCardForm } from './types';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { FileDown, ListPlus, Loader2, Plus, Upload, X } from 'lucide-react';
|
||||
import type { Card } from '../../../../types';
|
||||
import type { Card } from '../../../../shared/api-contract';
|
||||
import type { CardBatchModalProps } from '../types';
|
||||
|
||||
// BatchCardImportModal 负责卡密批量创建和单组库存追加的交互界面。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { Code, CreditCard, FileText, Image as ImageIcon } from 'lucide-react';
|
||||
import type { Card } from '../../../../types';
|
||||
import type { Card } from '../../../../shared/api-contract';
|
||||
|
||||
// CardIconProps 描述库存图标所需的卡密类型参数。
|
||||
interface CardIconProps {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Card } from '../../../types';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { appendCardData, batchCreateCards, getCards } from './api';
|
||||
import { useCardBatchActions, useCardsData } from './hooks';
|
||||
|
||||
@@ -212,4 +212,35 @@ describe('useCardsData 与 useCardBatchActions', /* 当前回调处理卡密库
|
||||
expect(hook.result.current.cards).toEqual([]);
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('批量创建在卸载时取消未完成请求', /* 当前回调验证批量表单卸载后不再允许晚到上传响应更新状态。 */ async () => {
|
||||
// uploadSignal 保存批量创建接口收到的取消信号。
|
||||
let uploadSignal: AbortSignal | undefined;
|
||||
batchCreateMock.mockImplementation(
|
||||
// pendingCreate 保持上传请求未完成,以便验证 Hook 卸载时主动取消。
|
||||
(_file, requestOptions) => {
|
||||
uploadSignal = requestOptions?.signal;
|
||||
return new Promise(/* pendingCreateExecutor 故意不完成上传 Promise,直到 Hook 卸载取消请求。 */ () => undefined);
|
||||
},
|
||||
);
|
||||
// hook 是带有上传文件的批量创建 Hook。
|
||||
const hook = renderHook(
|
||||
// batchHookFactory 创建批量操作 Hook。
|
||||
() => useCardBatchActions({ dataCards: [cardFixture], loadCards: loadCardsFixture }),
|
||||
);
|
||||
await act(
|
||||
// fileAction 写入将要上传的卡密文件。
|
||||
() => hook.result.current.setBatchFile(new File(['name'], 'cards.csv')),
|
||||
);
|
||||
await act(
|
||||
// createAction 发起尚未完成的上传但不等待其结束。
|
||||
() => { void hook.result.current.handleBatchCreate(); },
|
||||
);
|
||||
await waitFor(
|
||||
// uploadStartedAssertion 等待上传请求拿到取消信号。
|
||||
() => expect(uploadSignal).toBeDefined(),
|
||||
);
|
||||
hook.unmount();
|
||||
expect(uploadSignal?.aborted).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import { appendCardData, batchCreateCards, getCards } from './api';
|
||||
import type { Card } from '../../../types';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { canSubmitAppend, isCurrentCardRequest, previewAppendContent } from './batchState';
|
||||
import type { CardBatchState } from './types';
|
||||
|
||||
@@ -110,6 +110,18 @@ export const useCardBatchActions = (options: CardBatchOptions): CardBatchState =
|
||||
// lastAppendTarget 保存最近一次提交追加的目标 ID,供失败重试使用。
|
||||
const lastAppendTarget = useRef('');
|
||||
|
||||
useEffect(
|
||||
// 批量操作生命周期副作用在弹窗页面卸载时使未完成请求失效,防止晚到响应写入已销毁的表单状态。
|
||||
() => (
|
||||
// batchRequestCleanup 取消创建或追加请求,并推进代次屏蔽不响应 AbortSignal 的旧响应。
|
||||
() => {
|
||||
requestGeneration.current += 1;
|
||||
requestAbort.current?.abort();
|
||||
}
|
||||
),
|
||||
[],
|
||||
);
|
||||
|
||||
// appendPreview 按行派生追加预览,不重复存储派生状态。
|
||||
const appendPreview = useMemo(
|
||||
// 追加预览回调根据当前文本派生有效卡密行。
|
||||
|
||||
+4
-4
@@ -2,7 +2,7 @@
|
||||
import React from 'react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Card } from '../types';
|
||||
import type { Card } from '../../../../shared/api-contract';
|
||||
|
||||
// cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。
|
||||
const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({
|
||||
@@ -14,7 +14,7 @@ const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享
|
||||
updateCard: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/cards/hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({
|
||||
vi.mock('../hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({
|
||||
useCardsData: /* useCardsDataMock 返回固定卡密库存。 */ () => ({
|
||||
cards: cardListMocks.cards,
|
||||
setCards: vi.fn(),
|
||||
@@ -46,13 +46,13 @@ vi.mock('../app/features/cards/hooks', /* cardsHooksMockFactory 提供卡密库
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/cards/api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。 */ () => ({
|
||||
vi.mock('../api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。 */ () => ({
|
||||
createCard: cardListMocks.createCard,
|
||||
deleteCard: cardListMocks.deleteCard,
|
||||
updateCard: cardListMocks.updateCard,
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/cards/components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({
|
||||
vi.mock('../components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({
|
||||
BatchCardImportModal: /* BatchCardImportModalMock 表示批量导入弹窗替身。 */ () => null,
|
||||
}));
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Card } from '../types';
|
||||
import { Card } from '../../../../shared/api-contract';
|
||||
import { Plus, CreditCard, FileText, Image as ImageIcon, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, Search, SlidersHorizontal } from 'lucide-react';
|
||||
import { BatchCardImportModal } from '../app/features/cards/components/BatchCardImportModal';
|
||||
import { CardIcon } from '../app/features/cards/components/CardIcon';
|
||||
import { useCardBatchActions, useCardsData } from '../app/features/cards/hooks';
|
||||
import { useCardActions } from '../app/features/cards/cardActions';
|
||||
import { BatchCardImportModal } from '../components/BatchCardImportModal';
|
||||
import { CardIcon } from '../components/CardIcon';
|
||||
import { useCardBatchActions, useCardsData } from '../hooks';
|
||||
import { useCardActions } from '../cardActions';
|
||||
|
||||
// CardList 渲染卡密列表组件。
|
||||
const CardList: React.FC = () => {
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { Card, CardAppendResponse, CardBatchResponse } from '../../../types';
|
||||
import type { Card, CardAppendResponse, CardBatchResponse } from '../../../shared/api-contract';
|
||||
|
||||
// AddCardForm 描述新增卡密组弹窗中的可编辑字段。
|
||||
export interface AddCardForm {
|
||||
|
||||
@@ -1,12 +1,73 @@
|
||||
/** Chat feature 使用的会话、消息和账号运行状态 API。 */
|
||||
export {
|
||||
getAccountDetails,
|
||||
getAccountRuntimeStatuses,
|
||||
getChatMessagePage,
|
||||
getChatMessages,
|
||||
getChatSessionPage,
|
||||
getChatSessions,
|
||||
markChatRead,
|
||||
sendChatImage,
|
||||
sendChatMessage,
|
||||
} from '../../../services/api';
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
|
||||
/** 聊天账号选择器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
|
||||
/** 聊天运行提示读取账号连接状态索引。 */
|
||||
export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise<Record<string, { /** 当前连接状态。 */ state: NonNullable<AccountDetail['runtime_state']>; /** 状态说明。 */ message?: string; /** 是否已连接。 */ connected: boolean; /** 连续失败次数。 */ failures: number; /** 最近更新时间。 */ updated_at: string }>> => get('/api/v1/accounts/runtime-status', undefined, options);
|
||||
export interface ChatSessionPage { /** sessions 表示聊天会话列表。 */ sessions: ChatSession[]; /** has_more 表示是否存在更多数据。 */ has_more: boolean; /** next_cursor 表示下一页游标。 */ next_cursor?: number }
|
||||
|
||||
// getChatSessionPage 分页读取聊天会话。
|
||||
export const getChatSessionPage = async (accountId: string, cursor?: number, options?: RequestControlOptions, refresh = false): Promise<ChatSessionPage> => {
|
||||
// result 接口响应结果,用于当前 API 处理流程。
|
||||
const response = await get<unknown>('/api/v1/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined },
|
||||
refresh ? { timeoutMs: 60_000, ...options } : options);
|
||||
// result 是兼容直接分页对象和 data 包裹后的聊天会话分页。
|
||||
const result = objectFrom<Partial<ChatSessionPage>>(response, ['data', 'result']) || {};
|
||||
return { sessions: result.sessions || [], has_more: result.has_more === true, next_cursor: result.next_cursor };
|
||||
};
|
||||
|
||||
// getChatSessions 读取聊天会话列表。
|
||||
export const getChatSessions = async (accountId: string, options?: RequestControlOptions): Promise<ChatSession[]> =>
|
||||
(await getChatSessionPage(accountId, undefined, options)).sessions;
|
||||
|
||||
export interface ChatMessagePage {
|
||||
/** messages 表示聊天消息列表。 */ messages: ChatMessage[];
|
||||
/** has_more 表示是否存在更多数据。 */ has_more: boolean;
|
||||
/** next_cursor 表示下一页游标。 */ next_cursor?: number;
|
||||
/** session 表示会话。 */ session?: ChatSession;
|
||||
}
|
||||
|
||||
// getChatMessagePage 分页读取聊天消息。
|
||||
export const getChatMessagePage = async (accountId: string, chatId: string, cursor?: number, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessagePage> => {
|
||||
// result 接口响应结果,用于当前 API 处理流程。
|
||||
const response = await get<unknown>('/api/v1/chat/messages', {
|
||||
account_id: accountId, chat_id: chatId, cursor, before_id: beforeId,
|
||||
}, options);
|
||||
// result 是兼容直接分页对象和 data 包裹后的聊天消息分页。
|
||||
const result = objectFrom<Partial<ChatMessagePage>>(response, ['data', 'result']) || {};
|
||||
return { messages: result.messages || [], has_more: result.has_more === true, next_cursor: result.next_cursor, session: result.session };
|
||||
};
|
||||
|
||||
// getChatMessages 读取聊天消息列表。
|
||||
export const getChatMessages = async (accountId: string, chatId: string, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessage[]> =>
|
||||
(await getChatMessagePage(accountId, chatId, undefined, beforeId, options)).messages;
|
||||
|
||||
// sendChatMessage 发送聊天文本消息。
|
||||
export const sendChatMessage = async (input: {
|
||||
/** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string;
|
||||
/** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** text 表示文本。 */ text: string;
|
||||
}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => post('/api/v1/chat/messages', input, options);
|
||||
|
||||
// sendChatImage 发送聊天图片消息。
|
||||
export const sendChatImage = async (input: {
|
||||
/** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string;
|
||||
/** buyer_avatar_url 表示买家头像地址。 */ buyer_avatar_url?: string; /** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** image 表示图片数据。 */ image: File;
|
||||
}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => {
|
||||
// form 消息表单,用于当前 API 处理流程。
|
||||
const form = new FormData();
|
||||
Object.entries(input).forEach(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => form.append(key, value));
|
||||
return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options });
|
||||
};
|
||||
|
||||
// markChatRead 标记聊天消息已读。
|
||||
export const markChatRead = async (accountId: string, chatId: string, options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId }, options);
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../types';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
|
||||
import { useChat } from './hooks';
|
||||
|
||||
@@ -429,4 +429,43 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
expect(latestSocket?.close).toHaveBeenCalled();
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('切换或清空会话时取消未完成的历史消息分页', /* 当前回调验证历史分页不会在会话上下文失效后写入新会话状态。 */ async () => {
|
||||
// historySignal 保存历史分页接口收到的取消信号。
|
||||
let historySignal: AbortSignal | undefined;
|
||||
// hook 是已加载默认账号和会话的聊天 Hook。
|
||||
const hook = renderHook(
|
||||
// chatHookFactory 创建聊天 Hook。
|
||||
() => useChat(),
|
||||
);
|
||||
await waitFor(
|
||||
// activeChatAssertion 等待默认会话成为当前选择。
|
||||
() => expect(hook.result.current.activeChatID).toBe('chat-1'),
|
||||
);
|
||||
await waitFor(
|
||||
// messagesLoadedAssertion 等待首次消息分页完成并允许继续加载历史消息。
|
||||
() => expect(hook.result.current.messagesLoading).toBe(false),
|
||||
);
|
||||
getMessagePageMock.mockImplementationOnce(
|
||||
// pendingHistory 保持历史分页未完成,以便验证会话切换时主动取消。
|
||||
(_accountID, _chatID, _cursor, _oldestID, requestOptions) => {
|
||||
historySignal = requestOptions?.signal;
|
||||
return new Promise(/* pendingHistoryExecutor 故意不完成历史分页 Promise,直到会话切换取消请求。 */ () => undefined);
|
||||
},
|
||||
);
|
||||
await act(
|
||||
// olderMessagesAction 触发需要保持未完成的历史消息分页。
|
||||
() => { void hook.result.current.loadOlderMessages(); },
|
||||
);
|
||||
await waitFor(
|
||||
// historyStartedAssertion 等待历史分页请求建立取消信号。
|
||||
() => expect(historySignal).toBeDefined(),
|
||||
);
|
||||
await act(
|
||||
// clearChatAction 清空当前会话,使历史分页上下文立即失效。
|
||||
() => hook.result.current.setActiveChatID(''),
|
||||
);
|
||||
expect(historySignal?.aborted).toBe(true);
|
||||
hook.unmount();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import type React from 'react';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../types';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
|
||||
import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
@@ -128,6 +128,10 @@ export const useChat = (): UseChatResult => {
|
||||
const messageSequence = useRef(0);
|
||||
// messageController 保存当前消息请求控制器。
|
||||
const messageController = useRef<AbortController | null>(null);
|
||||
// olderSequence 隔离同一会话中被关闭、切换或替换的历史消息分页请求。
|
||||
const olderSequence = useRef(0);
|
||||
// olderController 保存当前历史消息分页请求,切换会话或卸载时必须由本 Hook 取消。
|
||||
const olderController = useRef<AbortController | null>(null);
|
||||
// contactSequence 隔离联系人分页产生的旧响应。
|
||||
const contactSequence = useRef(0);
|
||||
// contactController 保存当前联系人分页控制器。
|
||||
@@ -252,6 +256,11 @@ export const useChat = (): UseChatResult => {
|
||||
|
||||
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||
if (!activeAccountID || !activeChatID) {
|
||||
// 无有效会话时也推进消息与历史分页代次,避免晚到响应恢复已清空的消息列表。
|
||||
messageSequence.current += 1;
|
||||
olderSequence.current += 1;
|
||||
olderController.current?.abort();
|
||||
skipNextMessageScrollRef.current = false;
|
||||
setMessages([]);
|
||||
return;
|
||||
}
|
||||
@@ -290,9 +299,18 @@ export const useChat = (): UseChatResult => {
|
||||
sendSequence.current += 1;
|
||||
}, [activeAccountID, activeChatID]);
|
||||
|
||||
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||
// 会话切换时取消历史分页;新的消息加载拥有独立控制器,不能复用这个低优先级请求。
|
||||
olderSequence.current += 1;
|
||||
olderController.current?.abort();
|
||||
skipNextMessageScrollRef.current = false;
|
||||
}, [activeAccountID, activeChatID]);
|
||||
|
||||
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => /* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||
sessionController.current?.abort();
|
||||
messageController.current?.abort();
|
||||
olderSequence.current += 1;
|
||||
olderController.current?.abort();
|
||||
contactController.current?.abort();
|
||||
sendController.current?.abort();
|
||||
}, []);
|
||||
@@ -306,8 +324,12 @@ export const useChat = (): UseChatResult => {
|
||||
const previousHeight = container?.scrollHeight || 0;
|
||||
// sequence 请求序号。
|
||||
const sequence = messageSequence.current;
|
||||
// controller 请求取消控制器。
|
||||
// olderRequestSequence 标识本次历史分页,连续翻页、切换会话或卸载后旧分页不能写入状态。
|
||||
const olderRequestSequence = ++olderSequence.current;
|
||||
olderController.current?.abort();
|
||||
// controller 取消当前历史消息请求。
|
||||
const controller = new AbortController();
|
||||
olderController.current = controller;
|
||||
skipNextMessageScrollRef.current = true;
|
||||
setOlderLoading(true);
|
||||
setError('');
|
||||
@@ -316,18 +338,20 @@ export const useChat = (): UseChatResult => {
|
||||
const oldestID = messages[0]?.id;
|
||||
// page 页码。
|
||||
const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID, { signal: controller.signal });
|
||||
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return;
|
||||
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal) || olderRequestSequence !== olderSequence.current) return;
|
||||
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeOlderMessages(current, page.messages));
|
||||
setHasOlder(page.has_more);
|
||||
setHistoryCursor(page.next_cursor);
|
||||
requestAnimationFrame(/* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
if (container) container.scrollTop += container.scrollHeight - previousHeight;
|
||||
if (olderRequestSequence === olderSequence.current && !controller.signal.aborted && container) {
|
||||
container.scrollTop += container.scrollHeight - previousHeight;
|
||||
}
|
||||
});
|
||||
} catch (/* loadError 表示加载错误。 */ loadError) {
|
||||
skipNextMessageScrollRef.current = false;
|
||||
if (!isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载历史消息失败');
|
||||
} finally {
|
||||
setOlderLoading(false);
|
||||
if (olderRequestSequence === olderSequence.current) setOlderLoading(false);
|
||||
}
|
||||
}, [activeAccountID, activeChatID, hasOlder, historyCursor, messages, olderLoading]);
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw,
|
||||
Search, Send, Smile, UserRound, Wifi, WifiOff,
|
||||
} from 'lucide-react';
|
||||
import { useChat } from '../app/features/chat/hooks';
|
||||
import { useChat } from '../hooks';
|
||||
|
||||
// Chat 展示实时会话、消息分页和消息发送界面。
|
||||
const Chat: React.FC = () => {
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { ChatMessage, ChatSession } from '../../../types';
|
||||
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
|
||||
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ChatMessage, ChatSession } from '../../../types';
|
||||
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
|
||||
/** 按搜索条件筛选会话列表。 */
|
||||
export const filterChatSessions = (sessions: ChatSession[], search: string, unreadOnly: boolean): ChatSession[] => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../types';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
|
||||
/** 按账号保存会话列表。 */
|
||||
export type SessionsByAccount = Record<string, ChatSession[]>;
|
||||
|
||||
@@ -1,2 +1,64 @@
|
||||
/** Dashboard 数据接口集中导出,避免页面组件直接依赖通用 API 模块。 */
|
||||
export { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from '../../../services/api';
|
||||
import { get, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
import type { DashboardStatsResponse, Item, ItemListEnvelope, Order, OrderAnalyticsResponse, OrderStatus, ValidOrderResponse, ValidOrdersResponse } from '../../../shared/api-contract';
|
||||
import { formatLocalDate } from '../../../dateRange';
|
||||
|
||||
/** 仪表盘订单明细接口转换后的分页结果。 */
|
||||
export interface ValidOrdersResult {
|
||||
/** 当前时间范围的订单明细。 */
|
||||
orders: Order[];
|
||||
/** 服务端匹配到的订单总数。 */
|
||||
total: number;
|
||||
/** 是否存在未返回的后续订单。 */
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/** 将服务端订单状态映射为仪表盘可稳定展示的状态集合。 */
|
||||
const normalizeOrderStatus = (value: unknown): OrderStatus => {
|
||||
// status 是服务端返回的原始或历史订单状态。
|
||||
const status = String(value || '');
|
||||
if (status === 'paid') return 'pending_ship';
|
||||
return ['processing', 'pending_ship', 'shipped', 'completed', 'cancelled', 'refunding'].includes(status) ? status as OrderStatus : 'unknown';
|
||||
};
|
||||
|
||||
/** 读取仪表盘概览统计。 */
|
||||
export const getDashboardStats = async (options?: RequestControlOptions): Promise<DashboardStatsResponse> => get('/api/v1/analytics/dashboard', undefined, options);
|
||||
|
||||
/** 读取仪表盘商品索引,兼容历史 items 包装。 */
|
||||
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => {
|
||||
// response 是商品列表的原始 transport 响应。
|
||||
const response = await get<Item[] | ItemListEnvelope>('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options);
|
||||
// items 是从直接数组或历史包装中取出的商品集合。
|
||||
const items = collectionFrom<Item>(response, ['items', 'data', 'results']);
|
||||
return items.map(/* item 是当前需要兼容布尔标记的商品传输记录。 */ item => ({ ...item, id: item.id || `${item.cookie_id}-${item.item_id}`, is_multi_spec: item.is_multi_spec === true || item.is_multi_spec === 1, multi_quantity_delivery: item.multi_quantity_delivery === true || item.multi_quantity_delivery === 1 }));
|
||||
};
|
||||
|
||||
/** 读取指定自然日范围的订单统计,并显式传递浏览器时区偏移。 */
|
||||
export const getOrderAnalytics = async (range: number | { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string } = 7, options?: RequestControlOptions): Promise<OrderAnalyticsResponse> => {
|
||||
// dateRange 是标准化后的统计日期范围。
|
||||
let dateRange: { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string };
|
||||
if (typeof range === 'number') {
|
||||
// endDate 是计算默认区间使用的当前本地日期。
|
||||
const endDate = new Date();
|
||||
// startDate 是向前回溯指定天数后的本地日期。
|
||||
const startDate = new Date();
|
||||
startDate.setDate(startDate.getDate() - range);
|
||||
dateRange = { start_date: formatLocalDate(startDate), end_date: formatLocalDate(endDate) };
|
||||
} else {
|
||||
dateRange = range;
|
||||
}
|
||||
return get('/api/v1/analytics/orders', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options);
|
||||
};
|
||||
|
||||
/** 读取可参与仪表盘统计的订单并适配历史响应形状。 */
|
||||
export const getValidOrders = async (dateRange: { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string }, options?: RequestControlOptions): Promise<ValidOrdersResult> => {
|
||||
// response 是有效订单接口的未知兼容响应。
|
||||
const response = await get<unknown>('/api/v1/analytics/orders/valid', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options);
|
||||
// page 是移除历史 transport 包装后的分页元数据。
|
||||
const page = objectFrom<Partial<ValidOrdersResponse>>(response, ['data', 'result']) || {};
|
||||
// rows 是直接数组或历史 orders 包装中的原始订单。
|
||||
const rows = collectionFrom<ValidOrderResponse>(response, ['orders', 'data', 'items']);
|
||||
// orders 是转换状态、数量和稳定标识后的仪表盘订单模型。
|
||||
const orders = rows.map(/* row 是当前需要归一化状态与数量的有效订单 DTO。 */ row => ({ ...row, id: row.order_id, status: normalizeOrderStatus(row.status || row.order_status), order_status: normalizeOrderStatus(row.order_status), quantity: Number(row.quantity || 1) }));
|
||||
return { orders, total: Number(page.total ?? orders.length), truncated: page.truncated === true };
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { DashboardStats, Item, OrderAnalyticsResponse } from '../../../types';
|
||||
import type { DashboardStats, Item, OrderAnalyticsResponse } from '../../../shared/api-contract';
|
||||
import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api';
|
||||
import { useDashboard } from './hooks';
|
||||
import type { UseDashboardOptions } from './hooks';
|
||||
@@ -142,4 +142,33 @@ describe('useDashboard', /* 当前回调处理仪表盘并行请求和派生数
|
||||
expect(hook.result.current.status.range).toBe('success');
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('刷新期间丢弃忽略取消信号的旧概览响应', /* 当前回调验证概览请求即使底层实现没有响应取消,也不能覆盖刷新后的统计数据。 */ async () => {
|
||||
// resolveFirstStats 是首次概览统计请求的完成控制器。
|
||||
let resolveFirstStats: (value: DashboardStats) => void = () => undefined;
|
||||
// firstStatsRequest 是故意忽略 AbortSignal 的旧统计请求。
|
||||
const firstStatsRequest = new Promise<DashboardStats>(/* firstStatsExecutor 保存旧统计请求的完成函数。 */ resolve => { resolveFirstStats = resolve; });
|
||||
// refreshedStats 是刷新后应保留在页面中的权威概览数据。
|
||||
const refreshedStats = { ...statsFixture, total_orders: 99 };
|
||||
getStatsMock.mockReset();
|
||||
getStatsMock.mockReturnValueOnce(firstStatsRequest);
|
||||
getStatsMock.mockResolvedValueOnce(refreshedStats);
|
||||
// hook 是概览刷新竞态场景的 Hook 渲染结果。
|
||||
const hook = renderHook(renderDashboardHook);
|
||||
await act(
|
||||
// refreshAction 发起第二次概览加载并使首个请求过期。
|
||||
() => hook.result.current.refresh(),
|
||||
);
|
||||
await waitFor(
|
||||
// refreshedOverviewAssertion 等待新概览统计写入页面状态。
|
||||
() => expect(hook.result.current.data?.stats).toEqual(refreshedStats),
|
||||
);
|
||||
resolveFirstStats(statsFixture);
|
||||
await act(
|
||||
// staleOverviewResolveAction 完成被取消但仍返回的旧统计请求。
|
||||
async () => { await firstStatsRequest; },
|
||||
);
|
||||
expect(hook.result.current.data?.stats).toEqual(refreshedStats);
|
||||
hook.unmount();
|
||||
});
|
||||
});
|
||||
@@ -42,6 +42,8 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult =
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
// requestSequence 请求请求序号,负责当前功能中的对应处理。
|
||||
const requestSequence = useRef(0);
|
||||
// overviewSequence 隔离刷新后仍然完成的旧概览响应,避免忽略取消信号的底层实现覆盖新数据。
|
||||
const overviewSequence = useRef(0);
|
||||
// rangeSelection 范围选择,负责当前功能中的对应处理。
|
||||
const rangeSelection = useMemo(
|
||||
// selection 是当前时间范围的不可变快照。
|
||||
@@ -57,6 +59,8 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult =
|
||||
);
|
||||
|
||||
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||
// sequence 标识本轮概览请求,刷新或卸载后旧请求不得写入状态。
|
||||
const sequence = ++overviewSequence.current;
|
||||
// controller 请求取消控制器。
|
||||
const controller = new AbortController();
|
||||
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'loading', error: '' }));
|
||||
@@ -64,11 +68,11 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult =
|
||||
getDashboardStats({ signal: controller.signal }),
|
||||
getItems(undefined, { signal: controller.signal }),
|
||||
]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([stats, items]) => {
|
||||
if (controller.signal.aborted) return;
|
||||
if (!isCurrentDashboardRequest(overviewSequence.current, sequence, controller.signal)) return;
|
||||
setOverview({ stats, items, itemNames: buildItemNameMap(items) });
|
||||
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'success' }));
|
||||
}).catch(/* 当前回调处理用户交互或异步状态变化。 */ error => {
|
||||
if (controller.signal.aborted || isAbortError(error)) return;
|
||||
if (!isCurrentDashboardRequest(overviewSequence.current, sequence, controller.signal) || isAbortError(error)) return;
|
||||
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'error', error: errorMessage(error, '概览加载失败') }));
|
||||
});
|
||||
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
|
||||
|
||||
+2
-2
@@ -8,9 +8,9 @@ import { StatusBadge } from './Dashboard';
|
||||
// dashboardSource 仪表盘测试数据源。
|
||||
const dashboardSource = readFileSync(resolve(__dirname, 'Dashboard.tsx'), 'utf8');
|
||||
// trendChartSource 趋势图测试数据源。
|
||||
const trendChartSource = readFileSync(resolve(__dirname, '../app/features/dashboard/DashboardTrendChart.tsx'), 'utf8');
|
||||
const trendChartSource = readFileSync(resolve(__dirname, '../DashboardTrendChart.tsx'), 'utf8');
|
||||
// globalStyles 测试用全局样式。
|
||||
const globalStyles = readFileSync(resolve(__dirname, '../index.css'), 'utf8');
|
||||
const globalStyles = readFileSync(resolve(__dirname, '../../../../index.css'), 'utf8');
|
||||
|
||||
describe('Dashboard presentation safeguards', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
test('keeps order status badges on one line', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
import React, { useState } from 'react';
|
||||
import { OrderStatus } from '../types';
|
||||
import { getDateRange, TimeRange } from '../dateRange';
|
||||
import { formatLocalDateTime } from '../dateTime';
|
||||
import { OrderStatus } from '../../../../shared/api-contract';
|
||||
import { getDateRange, TimeRange } from '../../../../dateRange';
|
||||
import { formatLocalDateTime } from '../../../../dateTime';
|
||||
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
|
||||
import { Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
|
||||
import { useDashboard } from '../app/features/dashboard/hooks';
|
||||
import { DashboardTrendChart } from '../app/features/dashboard/DashboardTrendChart';
|
||||
import { useDashboard } from '../hooks';
|
||||
import { DashboardTrendChart } from '../DashboardTrendChart';
|
||||
|
||||
// cssColor 状态颜色样式。
|
||||
const cssColor = (token: string, alpha?: number) => (
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { OrderAnalytics } from '../../../types';
|
||||
import type { OrderAnalytics } from '../../../shared/api-contract';
|
||||
import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state';
|
||||
|
||||
// analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Item, OrderAnalytics } from '../../../types';
|
||||
import type { Item, OrderAnalytics } from '../../../shared/api-contract';
|
||||
import type { DateRange, TimeRange } from '../../../dateRange';
|
||||
import type { DashboardRangeSelection } from './types';
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../types';
|
||||
import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../shared/api-contract';
|
||||
import type { DateRange, TimeRange } from '../../../dateRange';
|
||||
|
||||
/** Dashboard 请求状态。 */
|
||||
|
||||
@@ -1,21 +1,164 @@
|
||||
// ItemList feature 通过本适配层访问商品、批量任务和发货地 API。
|
||||
export {
|
||||
getItems,
|
||||
getAccountDetails,
|
||||
syncItemsFromAccount,
|
||||
createItem,
|
||||
publishItem,
|
||||
recommendPublishCategory,
|
||||
previewItemPublishBatch,
|
||||
startItemPublishBatch,
|
||||
getItemPublishBatch,
|
||||
getItemPublishBatches,
|
||||
deleteItemPublishBatch,
|
||||
cancelItemPublishBatch,
|
||||
retryFailedItemPublishBatch,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
getShippingRules,
|
||||
} from '../../../services/api';
|
||||
export type { PublishLocation } from '../../../services/api';
|
||||
export { getPublishLocations } from '../../../services/amapLocation';
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
import { getPublishLocations } from '../../../services/amapLocation';
|
||||
import type { PublishLocation } from '../../../shared/api-contract';
|
||||
|
||||
/** 商品账号筛选器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
|
||||
/** 商品页面读取自动化发货规则的兼容列表。 */
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => get('/api/v1/automation-rules');
|
||||
|
||||
export { getPublishLocations };
|
||||
export type { PublishLocation } from '../../../shared/api-contract';
|
||||
// Items
|
||||
// normalizeBooleanFlag 归一化布尔标记。
|
||||
const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
value === true || value === 1 || value === '1';
|
||||
|
||||
// getItems 读取商品列表。
|
||||
export const getItems = async (cookieId?: string, options?: RequestControlOptions): Promise<Item[]> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const res = await get<unknown>('/api/v1/items', cookieId ? { cookie_id: cookieId } : undefined, options);
|
||||
// items 商品列表,用于当前 API 处理流程。
|
||||
const items = collectionFrom<Item>(res, ['items', 'data', 'results']);
|
||||
return items.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
|
||||
...item,
|
||||
id: item.id || `${item.cookie_id}-${item.item_id}`,
|
||||
is_multi_spec: normalizeBooleanFlag(item.is_multi_spec),
|
||||
is_multi_qty_ship: normalizeBooleanFlag(item.is_multi_qty_ship ?? item.multi_quantity_delivery),
|
||||
multi_quantity_delivery: normalizeBooleanFlag(item.multi_quantity_delivery ?? item.is_multi_qty_ship),
|
||||
}));
|
||||
}
|
||||
|
||||
// syncItemsFromAccount 从账号同步商品。
|
||||
export const syncItemsFromAccount = async (cookieId: string): Promise<ItemSyncResponse> => {
|
||||
return post('/api/v1/items/get-all-from-account', { cookie_id: cookieId });
|
||||
}
|
||||
|
||||
// deleteItem 删除商品。
|
||||
export const deleteItem = async (cookieId: string, itemId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/items/${cookieId}/${itemId}`);
|
||||
}
|
||||
|
||||
// createItem 创建商品。
|
||||
export const createItem = async (cookieId: string, data: Partial<Item>): Promise<OperationResponse> => {
|
||||
return post(`/api/v1/items/${cookieId}`, data);
|
||||
}
|
||||
|
||||
// publishItem 发布商品。
|
||||
export const publishItem = async (form: {
|
||||
/** cookie_id 表示登录凭证标识。 */ cookie_id: string;
|
||||
/** title 表示标题。 */ title: string;
|
||||
/** description 表示描述。 */ description: string;
|
||||
/** price 表示售价。 */ price: string;
|
||||
/** original_price 表示原始售价。 */ original_price?: string;
|
||||
/** quantity 表示数量。 */ quantity: string | number;
|
||||
/** postage_mode 表示运费模式。 */ postage_mode: string;
|
||||
/** postage 表示运费。 */ postage?: string;
|
||||
/** images 表示图片列表。 */ images: File[];
|
||||
/** location 表示地址。 */ location?: PublishLocation;
|
||||
}): Promise<ItemPublishResponse> => {
|
||||
// body 请求体,用于当前 API 处理流程。
|
||||
const body = new FormData();
|
||||
body.set('cookie_id', form.cookie_id);
|
||||
body.set('title', form.title);
|
||||
body.set('description', form.description);
|
||||
body.set('price', form.price);
|
||||
body.set('original_price', form.original_price || '');
|
||||
body.set('quantity', String(form.quantity));
|
||||
body.set('postage_mode', form.postage_mode);
|
||||
body.set('postage', form.postage || '');
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
for (const // file 上传文件,用于当前 API 处理流程。
|
||||
file of form.images) {
|
||||
body.append('images', file);
|
||||
}
|
||||
return postForm('/api/v1/items/publish', body);
|
||||
}
|
||||
|
||||
// recommendPublishCategory 推荐商品发布分类。
|
||||
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<CategoryRecommendationResponse> => {
|
||||
// 类目推荐成功响应使用共享 CategoryRecommendationResponse。
|
||||
// category 字段保留平台类目 ID、名称和频道类目 ID。
|
||||
// tb_cat_id 继续保持可选,兼容电子资料类目。
|
||||
// 请求仍携带账号 ID 和关键词。
|
||||
// 失败响应由共享 HTTP 错误结构处理。
|
||||
// 该类型收口不改变凭证刷新和错误处理。
|
||||
// 前端批量发布流程可直接复用 category。
|
||||
// 旧路径继续由现有 Vite 代理转发。
|
||||
return post('/api/v1/items/publish-categories/recommend', { cookie_id: cookieId, keyword });
|
||||
};
|
||||
|
||||
// previewItemPublishBatch 预览商品批量发布。
|
||||
export const previewItemPublishBatch = async (form: {
|
||||
/** file 表示上传文件。 */ file: File;
|
||||
/** imagesZip 表示图片压缩包。 */ imagesZip?: File | null;
|
||||
/** defaultCookieId 表示默认账号凭证标识。 */ defaultCookieId?: string;
|
||||
/** fallbackCategory 表示备用分类。 */ fallbackCategory: {
|
||||
/** catId 表示分类标识。 */ catId: string;
|
||||
/** catName 表示分类名称。 */ catName: string;
|
||||
/** channelCatId 表示渠道分类标识。 */ channelCatId?: string;
|
||||
/** tbCatId 表示淘宝分类标识。 */ tbCatId?: string;
|
||||
};
|
||||
/** location 表示地址。 */ location?: PublishLocation;
|
||||
}): Promise<ItemPublishBatchPreviewResponse> => {
|
||||
// body 请求体,用于当前 API 处理流程。
|
||||
const body = new FormData();
|
||||
body.set('file', form.file);
|
||||
if (form.imagesZip) body.set('images_zip', form.imagesZip);
|
||||
if (form.defaultCookieId) body.set('default_cookie_id', form.defaultCookieId);
|
||||
body.set('fallback_category_id', form.fallbackCategory.catId);
|
||||
body.set('fallback_category_name', form.fallbackCategory.catName);
|
||||
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
|
||||
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
return postForm('/api/v1/items/publish-batches/preview', body);
|
||||
}
|
||||
|
||||
// startItemPublishBatch 启动商品批量发布。
|
||||
export const startItemPublishBatch = async (previewId: string): Promise<BatchIDResponse> => {
|
||||
return post('/api/v1/items/publish-batches', { preview_id: previewId });
|
||||
}
|
||||
|
||||
// getItemPublishBatch 读取商品发布批次。
|
||||
export const getItemPublishBatch = async (batchId: string): Promise<ItemPublishBatchResponse> => {
|
||||
return get(`/api/v1/items/publish-batches/${batchId}`);
|
||||
}
|
||||
|
||||
// getItemPublishBatches 读取商品发布批次列表。
|
||||
export const getItemPublishBatches = async (limit = 20): Promise<ItemPublishBatchResponse[]> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const res = await get<unknown>('/api/v1/items/publish-batches', { limit });
|
||||
return collectionFrom<ItemPublishBatchResponse>(res, ['batches', 'data', 'items']);
|
||||
}
|
||||
|
||||
// deleteItemPublishBatch 删除商品发布批次。
|
||||
export const deleteItemPublishBatch = async (batchId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/items/publish-batches/${batchId}`);
|
||||
}
|
||||
|
||||
// cancelItemPublishBatch 取消商品发布批次。
|
||||
export const cancelItemPublishBatch = async (batchId: string): Promise<BatchCancelResponse> => {
|
||||
return post(`/api/v1/items/publish-batches/${batchId}/cancel`, {});
|
||||
}
|
||||
|
||||
// retryFailedItemPublishBatch 重试失败的商品发布任务。
|
||||
export const retryFailedItemPublishBatch = async (batchId: string): Promise<BatchIDResponse> => {
|
||||
return post(`/api/v1/items/publish-batches/${batchId}/retry-failed`, {});
|
||||
}
|
||||
|
||||
// updateItem 更新商品。
|
||||
export const updateItem = async (cookieId: string, itemId: string, data: Partial<Item>): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/items/${cookieId}/${itemId}`, data);
|
||||
}
|
||||
|
||||
/** 读取指定账号与商品的详情,用于编辑器恢复表单。 */
|
||||
export const getItemDetail = async (accountID: string, itemID: string): Promise<ItemDetailResponse> => get(`/api/v1/items/${accountID}/${itemID}`);
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchResponse } from '../../../types';
|
||||
import type { BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchResponse } from '../../../shared/api-contract';
|
||||
import {
|
||||
cancelItemPublishBatch,
|
||||
deleteItemPublishBatch,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { useState } from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Item } from '../../../types';
|
||||
import type { Item } from '../../../shared/api-contract';
|
||||
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
|
||||
import { useItemActions, type ItemActionsOptions } from './itemActions';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { Item } from '../../../types';
|
||||
import type { Item } from '../../../shared/api-contract';
|
||||
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
|
||||
import type { PublishLocation } from './api';
|
||||
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import type { Item } from '../types';
|
||||
import type { Item } from '../../../../shared/api-contract';
|
||||
import {
|
||||
getItems,
|
||||
getAccountDetails,
|
||||
getShippingRules,
|
||||
getItemPublishBatches,
|
||||
} from '../app/features/items/api';
|
||||
import type { AccountDetail, ShippingRule } from '../types';
|
||||
import type { ItemListProps } from '../app/features/items/types';
|
||||
import { useItemPublishBatch } from '../app/features/items/hooks';
|
||||
import { useItemActions } from '../app/features/items/itemActions';
|
||||
import { batchStatusClass, batchStatusText } from '../app/features/items/batchState';
|
||||
import { BatchPhaseIndicator } from '../app/features/items/components/BatchPhaseIndicator';
|
||||
} from '../api';
|
||||
import type { AccountDetail, ShippingRule } from '../../../../shared/api-contract';
|
||||
import type { ItemListProps } from '../types';
|
||||
import { useItemPublishBatch } from '../hooks';
|
||||
import { useItemActions } from '../itemActions';
|
||||
import { batchStatusClass, batchStatusText } from '../batchState';
|
||||
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
|
||||
|
||||
// formatItemPrice 将商品价格转换为本地化展示文本。
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { Item, AccountDetail, ShippingRule } from '../../../types';
|
||||
import type { Item, AccountDetail, ShippingRule } from '../../../shared/api-contract';
|
||||
import type { PublishLocation } from './api';
|
||||
|
||||
// ItemListProps 描述商品页面从父级接收的规则配置回调。
|
||||
|
||||
@@ -1,11 +1,134 @@
|
||||
export {
|
||||
createNotificationChannel,
|
||||
deleteNotificationChannel,
|
||||
getNotificationChannels,
|
||||
getSystemSettings,
|
||||
testNotificationChannel,
|
||||
updateNotificationChannel,
|
||||
updateSystemSettings,
|
||||
} from '../../../services/api';
|
||||
import { del, get, post, put, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import type { MutationIDResponse, NotificationBinding, NotificationChannel, NotificationChannelResponse, NotificationEventType, OperationResponse, SystemSettings } from '../../../shared/api-contract';
|
||||
|
||||
// notifications feature 通过本适配层声明渠道和 SMTP API 的来源。
|
||||
/** 通知渠道写入时使用的具名请求 DTO。 */
|
||||
export interface NotificationChannelRequest {
|
||||
/** 管理界面展示的渠道名称。 */
|
||||
name?: string;
|
||||
/** 后端支持的渠道类型。 */
|
||||
type?: string;
|
||||
/** 由各渠道表单构造的非敏感配置。 */
|
||||
config?: Record<string, unknown>;
|
||||
/** 需要订阅的系统事件。 */
|
||||
event_types?: NotificationEventType[];
|
||||
/** 渠道是否参与通知投递。 */
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
/** 将后端字符串或历史分隔文本转换为稳定事件类型列表。 */
|
||||
const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
|
||||
if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return [];
|
||||
try {
|
||||
// parsed 是解析后的历史 JSON 事件列表。
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[];
|
||||
} catch {
|
||||
// 非 JSON 历史值继续按分隔符兼容解析。
|
||||
}
|
||||
return raw.split(/[,\s;]+/).map(value => value.trim()).filter(Boolean) as NotificationEventType[];
|
||||
};
|
||||
|
||||
/** 将事件类型列表序列化为后端稳定保存的 JSON 文本。 */
|
||||
const stringifyNotificationEventTypes = (eventTypes?: NotificationEventType[]): string => {
|
||||
// uniqueTypes 是去重且去除空值后的事件列表。
|
||||
const uniqueTypes = Array.from(new Set((eventTypes || []).filter(Boolean)));
|
||||
return uniqueTypes.length > 0 ? JSON.stringify(uniqueTypes) : '';
|
||||
};
|
||||
|
||||
/** 把后端渠道 DTO 转换为通知编辑器使用的 UI 模型。 */
|
||||
const toNotificationChannel = (channel: NotificationChannelResponse): NotificationChannel => {
|
||||
// config 是解析失败时降级为空对象的渠道配置。
|
||||
let config: Record<string, unknown> = {};
|
||||
try {
|
||||
// parsed 是配置文本解析后的未知 JSON 值。
|
||||
const parsed: unknown = typeof channel.config === 'string' ? JSON.parse(channel.config) : channel.config;
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) config = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
// 历史损坏配置不阻止用户继续编辑渠道。
|
||||
}
|
||||
// type 是处理 ding_talk/lark 历史别名后的渠道类型。
|
||||
const type = (channel.type === 'ding_talk' ? 'dingtalk' : channel.type === 'lark' ? 'feishu' : channel.type) as NotificationChannel['type'];
|
||||
return { id: String(channel.id), name: channel.name, type, config, event_types: parseNotificationEventTypes(channel.event_types), enabled: channel.enabled, created_at: channel.created_at, updated_at: channel.updated_at };
|
||||
};
|
||||
|
||||
/** 获取全部通知渠道并转换为编辑器模型。 */
|
||||
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** 操作是否完成。 */ success: boolean; /** 渠道列表。 */ data: NotificationChannel[] }> => {
|
||||
// response 是渠道列表的原始传输响应。
|
||||
const response = await get<NotificationChannelResponse[] | { /** channels 是后端包装的渠道列表。 */ data?: NotificationChannelResponse[]; /** channels 是兼容字段。 */ channels?: NotificationChannelResponse[] }>('/api/v1/notifications/channels', undefined, options);
|
||||
// channels 是兼容直接数组与包装数组后的原始渠道列表。
|
||||
const channels = Array.isArray(response) ? response : response.data || response.channels || [];
|
||||
return { success: true, data: channels.map(toNotificationChannel) };
|
||||
};
|
||||
|
||||
/** 创建通知渠道,并在传输边界序列化配置与事件。 */
|
||||
export const createNotificationChannel = async (data: Required<Pick<NotificationChannelRequest, 'name' | 'type' | 'config'>> & NotificationChannelRequest, options?: RequestControlOptions): Promise<MutationIDResponse> => post('/api/v1/notifications/channels', { ...data, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types) }, options);
|
||||
|
||||
/** 更新通知渠道的可编辑字段。 */
|
||||
export const updateNotificationChannel = async (channelID: string, data: NotificationChannelRequest, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||
// payload 是已完成配置和事件序列化的更新请求。
|
||||
const payload: Record<string, unknown> = { ...data };
|
||||
if ('config' in data) payload.config = JSON.stringify(data.config);
|
||||
if ('event_types' in data) payload.event_types = stringifyNotificationEventTypes(data.event_types);
|
||||
return put(`/api/v1/notifications/channels/${channelID}`, payload, options);
|
||||
};
|
||||
|
||||
/** 删除指定通知渠道。 */
|
||||
export const deleteNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => del(`/api/v1/notifications/channels/${channelID}`, undefined, options);
|
||||
|
||||
/** 获取并展平按账号分组存储的消息通知绑定。 */
|
||||
export const getMessageNotifications = async (): Promise<{ /** 操作是否完成。 */ success: boolean; /** 展平后的绑定列表。 */ data: NotificationBinding[] }> => {
|
||||
// response 是按账号 ID 分组的通知绑定响应。
|
||||
const response = await get<Record<string, NotificationBinding[]>>('/api/v1/notifications/messages');
|
||||
// bindings 是供页面直接渲染的扁平绑定集合。
|
||||
const bindings: NotificationBinding[] = [];
|
||||
for (const /* accountID、channelBindings 是当前账号及其原始渠道绑定列表。 */ [accountID, channelBindings] of Object.entries(response || {})) {
|
||||
if (!Array.isArray(channelBindings)) continue;
|
||||
for (const /* binding 是当前待展平的单个账号渠道绑定。 */ binding of channelBindings) bindings.push({ ...binding, cookie_id: accountID });
|
||||
}
|
||||
return { success: true, data: bindings };
|
||||
};
|
||||
|
||||
/** 设置单个账号与渠道之间的启用状态。 */
|
||||
export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise<OperationResponse> => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_id: channelID, enabled });
|
||||
|
||||
/** 删除单个消息通知绑定。 */
|
||||
export const deleteMessageNotification = async (notificationID: string): Promise<OperationResponse> => del(`/api/v1/notifications/messages/${notificationID}`);
|
||||
|
||||
/** 删除指定账号的全部消息通知绑定。 */
|
||||
export const deleteAccountNotifications = async (accountID: string): Promise<OperationResponse> => del(`/api/v1/notifications/messages/account/${accountID}`);
|
||||
|
||||
/** 读取指定账号已绑定的通知渠道主键。 */
|
||||
export const getAccountBindings = async (accountID: string, options?: RequestControlOptions): Promise<number[]> => {
|
||||
// response 是账号渠道绑定的具名响应。
|
||||
const response = await get<{ /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[]; /** data 是兼容包装。 */ data?: { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[] } }>(`/api/v1/notifications/accounts/${accountID}/bindings`, undefined, options);
|
||||
return Array.isArray(response.channel_ids) ? response.channel_ids : Array.isArray(response.data?.channel_ids) ? response.data.channel_ids : [];
|
||||
};
|
||||
|
||||
/** 覆盖保存指定账号的通知渠道绑定。 */
|
||||
export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise<OperationResponse> => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_ids: channelIDs });
|
||||
|
||||
/** 向单一通知渠道发送测试投递。 */
|
||||
export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => post(`/api/v1/notifications/channels/${channelID}/test`, {}, options);
|
||||
|
||||
/** 将系统配置响应转换为通知 SMTP 表单使用的状态模型。 */
|
||||
const normalizeSystemSettings = (settings: Record<string, unknown>): SystemSettings => {
|
||||
// result 是不改变原始响应对象的设置副本。
|
||||
const result: Record<string, unknown> = { ...settings };
|
||||
if ('renewal_log_retention_days' in result) {
|
||||
// days 是已校验的日志保留天数。
|
||||
const days = Number(result.renewal_log_retention_days);
|
||||
result.renewal_log_retention_days = Number.isFinite(days) ? days : 10;
|
||||
}
|
||||
return result as SystemSettings;
|
||||
};
|
||||
|
||||
/** 获取通知 SMTP 编辑器需要的系统设置。 */
|
||||
export const getSystemSettings = async (options?: RequestControlOptions): Promise<SystemSettings> => {
|
||||
// response 是服务端可能以 data 包装的系统设置响应。
|
||||
const response = await get<{ /** data 是当前服务端系统设置。 */ data?: Record<string, unknown>; /** settings 是兼容字段。 */ settings?: Record<string, unknown> } & Record<string, unknown>>('/api/v1/settings/system', undefined, options);
|
||||
return normalizeSystemSettings(response.data || response.settings || response);
|
||||
};
|
||||
|
||||
/** 保存通知 SMTP 编辑器提交的系统设置。 */
|
||||
export const updateSystemSettings = async (settings: Partial<SystemSettings>, options?: RequestControlOptions): Promise<OperationResponse> => put('/api/v1/settings/system', settings, options);
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { Bell, Edit2, Loader2, Send, Trash2 } from 'lucide-react';
|
||||
import type { NotificationChannel } from '../../../../types';
|
||||
import type { NotificationChannel } from '../../../../shared/api-contract';
|
||||
import { notificationChannelTypes, notificationEventSummary } from '../state';
|
||||
|
||||
// NotificationChannelListProps 描述通知渠道列表的操作边界。
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Bell, Check, Eye, EyeOff, Loader2, X } from 'lucide-react';
|
||||
import { enableCustomSMTP } from '../../../../notificationEmailConfig';
|
||||
import { notificationChannelTypes } from '../state';
|
||||
import { NotificationEventSelector } from './NotificationEventSelector';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../types';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../shared/api-contract';
|
||||
import type { NotificationForm } from '../types';
|
||||
|
||||
// NotificationChannelModalProps 描述渠道编辑弹窗所需的状态和回调。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { Check } from 'lucide-react';
|
||||
import { notificationEvents } from '../state';
|
||||
import type { NotificationEventType } from '../../../../types';
|
||||
import type { NotificationEventType } from '../../../../shared/api-contract';
|
||||
|
||||
// NotificationEventSelectorProps 描述通知事件绑定组件的输入状态。
|
||||
export interface NotificationEventSelectorProps {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { Eye, EyeOff, Loader2, Mail, Save } from 'lucide-react';
|
||||
import type { SystemSettings } from '../../../../types';
|
||||
import type { SystemSettings } from '../../../../shared/api-contract';
|
||||
|
||||
// NotificationSmtpSettingsProps 描述系统 SMTP 配置面板所需的状态和事件。
|
||||
export interface NotificationSmtpSettingsProps {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { NotificationChannel, SystemSettings } from '../../../types';
|
||||
import type { NotificationChannel, SystemSettings } from '../../../shared/api-contract';
|
||||
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
|
||||
import { useNotifications } from './hooks';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../types';
|
||||
import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../shared/api-contract';
|
||||
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
|
||||
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, notificationErrorMessage, normalizeNotificationForm, validateNotificationForm } from './state';
|
||||
import type { NotificationForm, NotificationState } from './types';
|
||||
|
||||
+4
-4
@@ -1,9 +1,9 @@
|
||||
import React from 'react';
|
||||
import { Bell, Check, Loader2, Plus, RefreshCw, X } from 'lucide-react';
|
||||
import { NotificationChannelList } from '../app/features/notifications/components/NotificationChannelList';
|
||||
import { NotificationChannelModal } from '../app/features/notifications/components/NotificationChannelModal';
|
||||
import { NotificationSmtpSettings } from '../app/features/notifications/components/NotificationSmtpSettings';
|
||||
import { useNotifications } from '../app/features/notifications/hooks';
|
||||
import { NotificationChannelList } from '../components/NotificationChannelList';
|
||||
import { NotificationChannelModal } from '../components/NotificationChannelModal';
|
||||
import { NotificationSmtpSettings } from '../components/NotificationSmtpSettings';
|
||||
import { useNotifications } from '../hooks';
|
||||
|
||||
// NotificationsProps 描述通知页面接收的权限上下文。
|
||||
interface NotificationsProps {
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { NotificationChannel } from '../../../types';
|
||||
import type { NotificationChannel } from '../../../shared/api-contract';
|
||||
import type { NotificationForm } from './types';
|
||||
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, normalizeNotificationForm, notificationErrorMessage, notificationEventSummary, validateNotificationForm } from './state';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Bell, Mail, MessageCircle, Send as Telegram, Webhook } from 'lucide-react';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
|
||||
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../../../notificationEmailConfig';
|
||||
import type { NotificationChannelMeta, NotificationEventMeta, NotificationForm, NotificationPayload } from './types';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, ElementType, SetStateAction } from 'react';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
|
||||
|
||||
// NotificationField 描述通知渠道表单中的一个配置字段。
|
||||
export interface NotificationField {
|
||||
|
||||
@@ -1,13 +1,166 @@
|
||||
export {
|
||||
deleteOrder,
|
||||
getAccountDetails,
|
||||
getItems,
|
||||
getOrders,
|
||||
importOrders,
|
||||
manualShipOrder,
|
||||
syncOrders,
|
||||
syncSingleOrder,
|
||||
updateOrder,
|
||||
} from '../../../services/api';
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
|
||||
// 订单 feature 通过本文件声明服务 API 来源,页面不再直接依赖通用 API 模块。
|
||||
/** 订单筛选器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
|
||||
/** 订单关联商品展示读取当前商品索引。 */
|
||||
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options);
|
||||
|
||||
/** 管理员统计仍由订单域兼容 API 提供给历史管理页面。 */
|
||||
export const getAdminStats = async (): Promise<AdminStatsResponse> => get('/api/v1/admin/stats');
|
||||
// Orders
|
||||
// normalizeOrderStatus 归一化订单状态。
|
||||
const normalizeOrderStatus = (value: unknown): Order['status'] => {
|
||||
// status 状态值,用于当前 API 处理流程。
|
||||
const status = String(value || '');
|
||||
if (status === 'paid') return 'pending_ship';
|
||||
return ['processing', 'pending_ship', 'shipped', 'completed', 'cancelled', 'refunding'].includes(status)
|
||||
? status as Order['status']
|
||||
: 'unknown';
|
||||
};
|
||||
|
||||
// getOrders 读取订单列表。
|
||||
export const getOrders = async (
|
||||
cookieId?: string,
|
||||
status?: string,
|
||||
page: number = 1,
|
||||
pageSize: number = 20,
|
||||
search?: string,
|
||||
options?: RequestControlOptions,
|
||||
): Promise<PaginatedResponse<Order>> => {
|
||||
// params 请求参数,用于当前 API 处理流程。
|
||||
const params: any = { page, page_size: pageSize };
|
||||
if (cookieId) params.cookie_id = cookieId;
|
||||
if (status && status !== 'all') params.status = status;
|
||||
if (search?.trim()) params.search = search.trim();
|
||||
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const response = await get<unknown>('/api/v1/orders', params, options);
|
||||
// res 是兼容直接分页对象、orders 别名和 data 包裹后的订单响应。
|
||||
const res = objectFrom<Partial<PaginatedResponse<Order>> & { /** orders 是历史订单列表字段别名。 */ orders?: Order[] }>(response, ['data', 'result']) || {};
|
||||
|
||||
// Handle backend response variations
|
||||
// rawOrders 原始订单列表,用于当前 API 处理流程。
|
||||
const rawOrders = Array.isArray(res.orders) ? res.orders : collectionFrom<Order>(res.data, ['data', 'orders', 'items']);
|
||||
// orders 订单列表,用于当前 API 处理流程。
|
||||
const orders = rawOrders.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
|
||||
...item,
|
||||
id: item.id || item.order_id,
|
||||
status: normalizeOrderStatus(item.status || item.order_status),
|
||||
quantity: Number(item.quantity || 1),
|
||||
}));
|
||||
return {
|
||||
success: true,
|
||||
data: orders,
|
||||
total: res.total || orders.length,
|
||||
page: res.page || page,
|
||||
page_size: res.page_size || pageSize,
|
||||
total_pages: res.total_pages || 1
|
||||
};
|
||||
};
|
||||
|
||||
// getOrderDetail 读取订单详情。
|
||||
export const getOrderDetail = async (orderId: string): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: OrderDTOResponse }> => {
|
||||
// result 接口响应结果,用于当前 API 处理流程。
|
||||
const result = await get<OrderDetailResponse>(`/api/v1/orders/${orderId}`);
|
||||
return {
|
||||
success: true,
|
||||
data: result.data
|
||||
};
|
||||
};
|
||||
|
||||
// updateOrder 更新订单。
|
||||
export const updateOrder = async (orderId: string, data: Partial<Order>): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/orders/${orderId}`, data);
|
||||
};
|
||||
|
||||
// deleteOrder 删除订单。
|
||||
export const deleteOrder = async (orderId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/orders/${orderId}`);
|
||||
};
|
||||
|
||||
// syncOrders 同步订单。
|
||||
export const syncOrders = async (cookieId?: string, status?: string, options?: RequestControlOptions): Promise<OrderRefreshResponse> => {
|
||||
// formData 表单数据,用于当前 API 处理流程。
|
||||
const formData = new FormData();
|
||||
if (cookieId) formData.append('cookie_id', cookieId);
|
||||
if (status) formData.append('status', status);
|
||||
|
||||
// start 表示后台订单刷新任务创建响应。
|
||||
const start = await postForm<OrderRefreshJobStartResponse>('/api/v1/orders/refresh', formData, options);
|
||||
// cancelOnAbort 在调用方取消轮询时通知服务端停止同一后台任务。
|
||||
const cancelOnAbort = () => {
|
||||
void cancelOrderRefreshJob(start.job_id).catch(/* 取消请求失败时忽略网络错误,主请求仍按取消语义结束。 */ () => undefined);
|
||||
};
|
||||
options?.signal?.addEventListener('abort', cancelOnAbort, { once: true });
|
||||
// pollLimit 限制前端等待后台任务的轮询次数。
|
||||
const pollLimit = 180;
|
||||
// pollIndex 表示当前订单刷新任务状态轮询次数。
|
||||
let pollIndex = 0;
|
||||
try {
|
||||
while (pollIndex < pollLimit) {
|
||||
// job 表示当前轮询得到的后台任务状态。
|
||||
const job = await get<OrderRefreshJobStatusResponse>(`/api/v1/orders/refresh/${start.job_id}`, undefined, options);
|
||||
if (job.status === 'succeeded' && job.result) {
|
||||
return job.result;
|
||||
}
|
||||
if (job.status === 'failed' || job.status === 'cancelled') {
|
||||
throw new Error(job.error_message || '订单刷新任务失败');
|
||||
}
|
||||
// waitMs 是下一次任务状态轮询前的等待时间。
|
||||
const waitMs = 500;
|
||||
await new Promise<void>(/* 轮询等待器负责等待下一次任务状态查询。 */ (resolve, reject) => {
|
||||
// abort 负责响应调用方取消轮询。
|
||||
const abort = () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
reject(new Error('请求已取消'));
|
||||
};
|
||||
// timer 表示当前轮询等待定时器。
|
||||
const timer = globalThis.setTimeout(/* 轮询完成回调清理取消监听并结束等待。 */ () => {
|
||||
options?.signal?.removeEventListener('abort', abort);
|
||||
resolve();
|
||||
}, waitMs);
|
||||
if (!options?.signal) return;
|
||||
if (options.signal.aborted) abort();
|
||||
else options.signal.addEventListener('abort', abort, { once: true });
|
||||
});
|
||||
pollIndex += 1;
|
||||
}
|
||||
} finally {
|
||||
options?.signal?.removeEventListener('abort', cancelOnAbort);
|
||||
}
|
||||
throw new Error('订单刷新任务等待超时');
|
||||
};
|
||||
|
||||
// cancelOrderRefreshJob 请求取消当前用户的订单刷新后台任务。
|
||||
export const cancelOrderRefreshJob = async (jobId: string): Promise<OrderRefreshJobCancelResponse> => {
|
||||
return del(`/api/v1/orders/refresh/${jobId}`);
|
||||
};
|
||||
|
||||
// syncSingleOrder 同步单个订单。
|
||||
export const syncSingleOrder = async (orderId: string): Promise<OrderSingleRefreshResponse> => {
|
||||
return post(`/api/v1/orders/${orderId}/refresh`);
|
||||
};
|
||||
|
||||
// manualShipOrder 手动发货订单。
|
||||
export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise<OrderBatchResponse> => {
|
||||
return post('/api/v1/orders/manual-ship', {
|
||||
order_ids: orderIds,
|
||||
ship_mode: shipMode,
|
||||
});
|
||||
}
|
||||
|
||||
// importOrders 导入订单。
|
||||
export const importOrders = async (data: Partial<Order>[] | FormData, options?: RequestControlOptions): Promise<OrderBatchResponse> => {
|
||||
// isFormData 是否为表单请求,用于当前 API 处理流程。
|
||||
const isFormData = data instanceof FormData;
|
||||
return isFormData ? postForm('/api/v1/orders/import', data, options) : post('/api/v1/orders/import', data, options);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { Search, User as UserIcon } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../types';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
import { orderStatusOptions } from '../state';
|
||||
|
||||
// OrderFilterBarProps 描述订单状态、账号和文本筛选所需的页面状态。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, Item } from '../../../types';
|
||||
import type { AccountDetail, Item } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getItems, getOrders, importOrders } from './api';
|
||||
import { useOrderImport, useOrderQuery } from './hooks';
|
||||
|
||||
@@ -287,4 +287,37 @@ describe('useOrderQuery 与 useOrderImport', /* 当前回调处理订单查询
|
||||
expect(hook.result.current.orders).toEqual([orderFixture]);
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('订单导入在卸载时取消未完成上传', /* 当前回调验证导入弹窗离开页面后不会接受忽略取消信号的旧响应。 */ async () => {
|
||||
// importSignal 保存导入接口收到的取消信号。
|
||||
let importSignal: AbortSignal | undefined;
|
||||
importOrdersMock.mockImplementation(
|
||||
// pendingImport 保持文件上传未完成,以便观察 Hook 卸载时的取消行为。
|
||||
(_formData, requestOptions) => {
|
||||
importSignal = requestOptions?.signal;
|
||||
return new Promise(/* pendingImportExecutor 故意不完成导入 Promise,直到 Hook 卸载取消请求。 */ () => undefined);
|
||||
},
|
||||
);
|
||||
// refreshOrders 是导入成功后刷新订单列表的替身。
|
||||
const refreshOrders = vi.fn().mockResolvedValue(undefined);
|
||||
// hook 是订单导入 Hook 渲染结果。
|
||||
const hook = renderHook(
|
||||
// importHookFactory 使用稳定的列表刷新回调创建导入 Hook。
|
||||
() => useOrderImport(refreshOrders),
|
||||
);
|
||||
await act(
|
||||
// fileAction 写入符合格式要求的订单导入文件。
|
||||
() => hook.result.current.setImportFile(new File(['order'], 'orders.csv')),
|
||||
);
|
||||
await act(
|
||||
// importAction 启动上传但不等待未完成网络请求。
|
||||
() => { void hook.result.current.handleImportOrders(); },
|
||||
);
|
||||
await waitFor(
|
||||
// importStartedAssertion 等待导入请求建立取消信号。
|
||||
() => expect(importSignal).toBeDefined(),
|
||||
);
|
||||
hook.unmount();
|
||||
expect(importSignal?.aborted).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { AccountDetail, Item, Order } from '../../../types';
|
||||
import type { AccountDetail, Item, Order } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getItems, getOrders, importOrders } from './api';
|
||||
import { canSubmitOrderImport, isCurrentOrderRequest, normalizeOrderImportResult, orderErrorMessage, validateOrderImportFile } from './state';
|
||||
import type { OrderImportState, OrderQueryState } from './types';
|
||||
@@ -249,6 +249,18 @@ export const useOrderImport = (loadOrders: () => Promise<void>): OrderImportStat
|
||||
// importAbort 保存当前导入请求的取消控制器。
|
||||
const importAbort = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(
|
||||
// 导入生命周期副作用负责在弹窗组件卸载时取消上传并禁止旧结果继续更新 React 状态。
|
||||
() => (
|
||||
// importRequestCleanup 推进导入代次并中止尚未结束的 multipart 请求。
|
||||
() => {
|
||||
importGeneration.current += 1;
|
||||
importAbort.current?.abort();
|
||||
}
|
||||
),
|
||||
[],
|
||||
);
|
||||
|
||||
// openImportModal 打开订单导入弹窗并重置上一次结果。
|
||||
const openImportModal = useCallback(
|
||||
// 打开弹窗回调清理上一次导入状态。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Order } from '../../../types';
|
||||
import type { Order } from '../../../shared/api-contract';
|
||||
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api';
|
||||
import { useOrderActions } from './orderActions';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { Order, OrderStatus } from '../../../types';
|
||||
import type { Order, OrderStatus } from '../../../shared/api-contract';
|
||||
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api';
|
||||
|
||||
// OrderShipMode 表示订单发货操作的两种业务模式。
|
||||
|
||||
+5
-5
@@ -2,7 +2,7 @@
|
||||
import React from 'react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Order } from '../types';
|
||||
import type { Order } from '../../../../shared/api-contract';
|
||||
|
||||
// orderListMocks 保存订单页面测试使用的 Hook、API 和子组件替身。
|
||||
const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共享替身。 */ () => ({
|
||||
@@ -24,7 +24,7 @@ const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共
|
||||
deleteOrder: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/orders/hooks', /* ordersHooksMockFactory 提供订单查询与导入 Hook 替身。 */ () => ({
|
||||
vi.mock('../hooks', /* ordersHooksMockFactory 提供订单查询与导入 Hook 替身。 */ () => ({
|
||||
useOrderQuery: /* useOrderQueryMock 返回订单页面固定查询状态。 */ () => ({
|
||||
orders: orderListMocks.orders,
|
||||
accounts: [{ id: 'account-1', enabled: true, auto_confirm: false, nickname: 'Alpha', remark: '主账号' }],
|
||||
@@ -57,7 +57,7 @@ vi.mock('../app/features/orders/hooks', /* ordersHooksMockFactory 提供订单
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/orders/api', /* ordersApiMockFactory 提供订单页面动作 API 替身。 */ () => ({
|
||||
vi.mock('../api', /* ordersApiMockFactory 提供订单页面动作 API 替身。 */ () => ({
|
||||
syncOrders: orderListMocks.syncOrders,
|
||||
syncSingleOrder: orderListMocks.syncSingleOrder,
|
||||
manualShipOrder: orderListMocks.manualShipOrder,
|
||||
@@ -65,7 +65,7 @@ vi.mock('../app/features/orders/api', /* ordersApiMockFactory 提供订单页面
|
||||
deleteOrder: orderListMocks.deleteOrder,
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/orders/components/OrderFilterBar', /* filterBarMockFactory 提供订单筛选栏替身。 */ () => {
|
||||
vi.mock('../components/OrderFilterBar', /* filterBarMockFactory 提供订单筛选栏替身。 */ () => {
|
||||
// OrderFilterBarMock 暴露筛选栏的状态切换和输入事件。
|
||||
const OrderFilterBarMock: React.FC<any> = (props /* props 表示筛选栏状态和事件回调。 */) => (
|
||||
<div data-testid="order-filter-bar">
|
||||
@@ -80,7 +80,7 @@ vi.mock('../app/features/orders/components/OrderFilterBar', /* filterBarMockFact
|
||||
return { OrderFilterBar: OrderFilterBarMock };
|
||||
});
|
||||
|
||||
vi.mock('../app/features/orders/components/OrderImportModal', /* importModalMockFactory 提供订单导入弹窗替身。 */ () => ({
|
||||
vi.mock('../components/OrderImportModal', /* importModalMockFactory 提供订单导入弹窗替身。 */ () => ({
|
||||
OrderImportModal: /* OrderImportModalMock 表示订单导入弹窗替身。 */ (props: any) => props.showImportModal ? <div data-testid="import-modal">订单导入弹窗</div> : null,
|
||||
}));
|
||||
|
||||
+6
-6
@@ -1,12 +1,12 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import type { OrderStatus } from '../types';
|
||||
import { OrderFilterBar } from '../app/features/orders/components/OrderFilterBar';
|
||||
import { OrderImportModal } from '../app/features/orders/components/OrderImportModal';
|
||||
import { useOrderImport, useOrderQuery } from '../app/features/orders/hooks';
|
||||
import { useOrderActions } from '../app/features/orders/orderActions';
|
||||
import type { OrderStatus } from '../../../../shared/api-contract';
|
||||
import { OrderFilterBar } from '../components/OrderFilterBar';
|
||||
import { OrderImportModal } from '../components/OrderImportModal';
|
||||
import { useOrderImport, useOrderQuery } from '../hooks';
|
||||
import { useOrderActions } from '../orderActions';
|
||||
import { Truck, RefreshCw, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, ExternalLink, Trash2 } from 'lucide-react';
|
||||
import { formatLocalDateTime } from '../dateTime';
|
||||
import { formatLocalDateTime } from '../../../../dateTime';
|
||||
|
||||
// StatusBadge 渲染订单状态徽标。
|
||||
const StatusBadge: React.FC<{ /** status 表示状态。 */ status: OrderStatus }> = ({ status }) => {
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { AccountDetail, Item, Order, OrderStatus } from '../../../types';
|
||||
import type { AccountDetail, Item, Order, OrderStatus } from '../../../shared/api-contract';
|
||||
|
||||
// OrderImportRowResult 描述订单导入接口返回的单行处理结果。
|
||||
export interface OrderImportRowResult {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import ReactDOMServer from 'react-dom/server';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import type { NotificationChannel } from '../../types';
|
||||
import type { SystemSettings } from '../../types';
|
||||
import type { NotificationChannel } from '../../shared/api-contract';
|
||||
import type { SystemSettings } from '../../shared/api-contract';
|
||||
import { CardIcon } from './cards/components/CardIcon';
|
||||
import { BatchPhaseIndicator } from './items/components/BatchPhaseIndicator';
|
||||
import { NotificationChannelList } from './notifications/components/NotificationChannelList';
|
||||
|
||||
@@ -1,24 +1,355 @@
|
||||
// 规则 feature 只通过本适配层访问共享 API,组件不直接依赖网络客户端。
|
||||
export {
|
||||
clearDefaultReplyRecords,
|
||||
deleteDefaultReply,
|
||||
deleteReplyRule,
|
||||
deleteShippingRule,
|
||||
getAccountDetails,
|
||||
getCards,
|
||||
getDefaultReplies,
|
||||
getDefaultReply,
|
||||
getItems,
|
||||
getAutomationIssues,
|
||||
getReplyRules,
|
||||
getShippingRules,
|
||||
getShippingRulesPage,
|
||||
updateDefaultReply,
|
||||
updateReplyRule,
|
||||
updateShippingRule,
|
||||
resolveAutomationRun,
|
||||
resolveDeferredAutomationTask,
|
||||
} from '../../../services/api';
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
|
||||
// 规则异常类型由共享 API 层定义,feature 通过类型重导出保持边界稳定。
|
||||
export type { AutomationRunIssue, DeferredAutomationIssue } from '../../../services/api';
|
||||
/** 自动化规则筛选器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
|
||||
/** 自动化动作编辑器读取可选卡券组。 */
|
||||
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => get('/api/v1/cards', undefined, options);
|
||||
|
||||
/** 自动化规则商品选择器读取商品索引。 */
|
||||
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options);
|
||||
// Rules - 自动化规则
|
||||
const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
|
||||
id: String(item.id),
|
||||
name: item.name || '',
|
||||
trigger_type: item.trigger_type || 'order_paid',
|
||||
item_keyword: item.item_title || item.item_id || '',
|
||||
cookie_id: item.cookie_id || '',
|
||||
item_id: item.item_id || '',
|
||||
item_title: item.item_title || '',
|
||||
card_group_id: Number((item.actions || []).find(/* 当前回调用于处理集合元素或接口响应。 */ (a: any) => a.action_type === 'send_card')?.card_id || 0),
|
||||
card_group_name: (item.actions || []).find(/* 当前回调用于处理集合元素或接口响应。 */ (a: any) => a.action_type === 'send_card')?.card_name || '',
|
||||
priority: item.priority || 100,
|
||||
enabled: item.enabled || false,
|
||||
config_json: item.config_json || '{}',
|
||||
actions: (item.actions || []).map(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => ({
|
||||
id: action.id ? String(action.id) : undefined,
|
||||
action_type: action.action_type,
|
||||
card_id: Number(action.card_id || 0),
|
||||
card_name: action.card_name || '',
|
||||
delivery_count: Number(action.delivery_count || 1),
|
||||
message_template: action.message_template || '',
|
||||
delay_seconds: Number(action.delay_seconds || 0),
|
||||
config_json: action.config_json || '{}',
|
||||
enabled: action.enabled !== false,
|
||||
sort_order: Number(action.sort_order || 0),
|
||||
})),
|
||||
variants: (item.actions || [])
|
||||
.filter(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => action.action_type === 'send_card')
|
||||
.map(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => {
|
||||
// cfg 动作配置,用于当前 API 处理流程。
|
||||
let cfg: any = {};
|
||||
try { cfg = JSON.parse(action.config_json || '{}'); } catch {}
|
||||
return {
|
||||
id: action.id ? String(action.id) : undefined,
|
||||
spec_name: cfg.spec_name || '',
|
||||
spec_value: cfg.spec_value || '',
|
||||
card_id: Number(action.card_id || 0),
|
||||
card_name: action.card_name || '',
|
||||
delivery_count: Number(action.delivery_count || 1),
|
||||
enabled: action.enabled !== false,
|
||||
delay_override: cfg.delay_override === true,
|
||||
delay_seconds: Number(action.delay_seconds || 0),
|
||||
config_json: action.config_json || '{}',
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
// getShippingRules 读取发货规则列表。
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const res = await get<unknown>('/api/v1/automation-rules');
|
||||
// rules 规则列表,用于当前 API 处理流程。
|
||||
const rules = collectionFrom<AutomationRuleResponse>(res, ['data', 'rules', 'items']);
|
||||
return normalizeShippingRules(rules);
|
||||
}
|
||||
|
||||
export interface ShippingRuleListParams {
|
||||
/** cookieId 表示登录凭证标识。 */ cookieId?: string;
|
||||
/** triggerType 表示触发类型。 */ triggerType?: AutomationTriggerType | '';
|
||||
/** enabled 表示启用状态。 */ enabled?: boolean;
|
||||
/** search 表示搜索条件。 */ search?: string;
|
||||
/** page 表示页码。 */ page?: number;
|
||||
/** pageSize 表示每页数量。 */ pageSize?: number;
|
||||
}
|
||||
|
||||
// getShippingRulesPage 分页读取发货规则。
|
||||
export const getShippingRulesPage = async ({
|
||||
cookieId,
|
||||
triggerType,
|
||||
enabled,
|
||||
search,
|
||||
page: requestedPage = 1,
|
||||
pageSize = 10,
|
||||
}: ShippingRuleListParams = {}): Promise<PaginatedResponse<ShippingRule>> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const response = await get<unknown>('/api/v1/automation-rules', {
|
||||
page: requestedPage,
|
||||
page_size: pageSize,
|
||||
cookie_id: cookieId || undefined,
|
||||
trigger_type: triggerType || undefined,
|
||||
enabled,
|
||||
search: search?.trim() || undefined,
|
||||
});
|
||||
// rules 规则列表,用于当前 API 处理流程。
|
||||
// page 是兼容直接分页对象和 data 包裹后的分页元数据。
|
||||
const pageMeta = objectFrom<Partial<AutomationRulePageResponse>>(response, ['data', 'result']) || {};
|
||||
// rules 是归一化后的自动化规则列表。
|
||||
const rules = normalizeShippingRules(collectionFrom<AutomationRuleResponse>(response, ['data', 'rules', 'items']));
|
||||
return {
|
||||
success: true,
|
||||
data: rules,
|
||||
total: Number(pageMeta.total ?? rules.length),
|
||||
page: Number(pageMeta.page ?? requestedPage),
|
||||
page_size: Number(pageMeta.page_size ?? pageSize),
|
||||
total_pages: Number(pageMeta.total_pages ?? (rules.length ? 1 : 0)),
|
||||
trigger_counts: Object.fromEntries(
|
||||
Object.entries(pageMeta.trigger_counts || {}).map(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => [key, Number(value)]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// orderAutomationActions 构建订单自动化动作。
|
||||
const orderAutomationActions = (triggerType: string, actions: AutomationAction[]) => {
|
||||
if (triggerType !== 'order_paid') {
|
||||
return actions.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: action.sort_order || index + 1 }));
|
||||
}
|
||||
// sendCards 发送Cards。
|
||||
const sendCards = actions
|
||||
.filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type === 'send_card')
|
||||
.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: index + 1 }));
|
||||
// others 其他动作列表,用于当前 API 处理流程。
|
||||
const others = actions.filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment');
|
||||
return [
|
||||
...sendCards,
|
||||
...others.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: sendCards.length + index + 1 })),
|
||||
{ action_type: 'confirm_shipment' as const, enabled: true, sort_order: sendCards.length + others.length + 1 },
|
||||
];
|
||||
};
|
||||
|
||||
// updateShippingRule 更新发货规则。
|
||||
export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<OperationResponse | MutationIDResponse> => {
|
||||
// triggerType 触发类型,用于当前 API 处理流程。
|
||||
const triggerType = rule.trigger_type || 'order_paid';
|
||||
// triggerName 触发名称,用于当前 API 处理流程。
|
||||
const triggerName: Record<string, string> = {
|
||||
order_paid: '付款后自动发货',
|
||||
buyer_reviewed: '评价后发送赠品',
|
||||
review_missing_timeout: '超时未评价求评价',
|
||||
};
|
||||
// generatedName 生成d名称。
|
||||
const generatedName = [
|
||||
triggerName[triggerType] || '自动化规则',
|
||||
rule.item_title || rule.item_id || rule.cookie_id || '',
|
||||
].filter(Boolean).join(' - ');
|
||||
// preservedNonCardActions 保留的非卡密动作,用于当前 API 处理流程。
|
||||
const preservedNonCardActions = (rule.actions || []).filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment');
|
||||
// baseActions 基础动作列表,用于当前 API 处理流程。
|
||||
const baseActions: AutomationAction[] = rule.variants && rule.variants.length > 0
|
||||
? [...rule.variants.map(/* 当前回调用于处理集合元素或接口响应。 */ (variant, index) => ({
|
||||
action_type: 'send_card' as const,
|
||||
card_id: variant.card_id,
|
||||
delivery_count: variant.delivery_count || 1,
|
||||
enabled: variant.enabled !== false,
|
||||
sort_order: index + 1,
|
||||
delay_seconds: variant.delay_seconds || 0,
|
||||
config_json: JSON.stringify({
|
||||
spec_name: variant.spec_name || '',
|
||||
spec_value: variant.spec_value || '',
|
||||
delay_override: variant.delay_override === true,
|
||||
}),
|
||||
})), ...preservedNonCardActions]
|
||||
: (rule.actions && rule.actions.length > 0 ? rule.actions : [{
|
||||
action_type: 'send_card' as const,
|
||||
card_id: rule.card_group_id || 0,
|
||||
delivery_count: 1,
|
||||
enabled: true,
|
||||
sort_order: 1,
|
||||
}]);
|
||||
// actions 动作列表,用于当前 API 处理流程。
|
||||
const actions = orderAutomationActions(triggerType, baseActions);
|
||||
// payload 请求载荷,用于当前 API 处理流程。
|
||||
const payload = {
|
||||
cookie_id: rule.cookie_id || '',
|
||||
item_id: rule.item_id || '',
|
||||
name: (rule.name || '').trim() || generatedName || '自动化规则',
|
||||
trigger_type: triggerType,
|
||||
enabled: rule.enabled ?? true,
|
||||
priority: rule.priority || 100,
|
||||
config_json: rule.config_json || '{}',
|
||||
actions: actions.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({
|
||||
action_type: action.action_type,
|
||||
card_id: action.card_id || 0,
|
||||
delivery_count: action.delivery_count || 1,
|
||||
message_template: action.message_template || '',
|
||||
delay_seconds: action.delay_seconds || 0,
|
||||
config_json: action.config_json || '{}',
|
||||
enabled: action.enabled !== false,
|
||||
sort_order: action.sort_order || index + 1,
|
||||
})),
|
||||
};
|
||||
return rule.id ? put(`/api/v1/automation-rules/${rule.id}`, payload) : post('/api/v1/automation-rules', payload);
|
||||
}
|
||||
|
||||
// deleteShippingRule 删除发货规则。
|
||||
export const deleteShippingRule = async (id: string): Promise<OperationResponse> => del(`/api/v1/automation-rules/${id}`);
|
||||
|
||||
export interface AutomationRunIssue {
|
||||
/** id 表示标识。 */ id: number;
|
||||
/** cookie_id 表示登录凭证标识。 */ cookie_id: string;
|
||||
/** order_id 表示订单标识。 */ order_id: string;
|
||||
/** trigger_type 表示触发条件类型。 */ trigger_type: string;
|
||||
/** error_message 表示错误消息。 */ error_message: string;
|
||||
/** issue_kind 表示问题类型。 */ issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed';
|
||||
/** allowed_resolutions 表示允许的解决方式。 */ allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>;
|
||||
/** action_cursor 表示动作游标。 */ action_cursor: number;
|
||||
/** sent_count 表示已发送数量。 */ sent_count: number;
|
||||
/** updated_at 表示最后更新时间。 */ updated_at: string;
|
||||
}
|
||||
|
||||
export interface DeferredAutomationIssue {
|
||||
/** id 表示标识。 */ id: number;
|
||||
/** cookie_id 表示登录凭证标识。 */ cookie_id: string;
|
||||
/** trigger_type 表示触发条件类型。 */ trigger_type: string;
|
||||
/** error_message 表示错误消息。 */ error_message: string;
|
||||
/** attempt_count 表示尝试次数。 */ attempt_count: number;
|
||||
/** updated_at 表示最后更新时间。 */ updated_at: string;
|
||||
}
|
||||
|
||||
// getAutomationIssues 读取自动化问题列表。
|
||||
export const getAutomationIssues = async (): Promise<{ /** runs 表示运行记录。 */ runs: AutomationRunIssue[]; /** pending_tasks 表示待处理任务列表。 */ pending_tasks: DeferredAutomationIssue[] }> => {
|
||||
// response 是兼容直接问题对象、data 包裹和 null 的自动化问题响应。
|
||||
const response = await get<unknown>('/api/v1/automation-issues');
|
||||
// result 是去除历史包裹后的自动化问题对象。
|
||||
const result = objectFrom<Partial<AutomationIssuesEnvelope>>(response, ['data', 'result']) || {};
|
||||
return {
|
||||
runs: Array.isArray(result?.runs) ? result.runs : [],
|
||||
pending_tasks: Array.isArray(result?.pending_tasks) ? result.pending_tasks : [],
|
||||
};
|
||||
};
|
||||
|
||||
// resolveAutomationRun 处理自动化运行记录。
|
||||
export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise<OperationResponse> =>
|
||||
post(`/api/v1/automation-runs/${id}/resolve`, { resolution });
|
||||
|
||||
// resolveDeferredAutomationTask 处理延迟自动化任务。
|
||||
export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise<OperationResponse> =>
|
||||
post(`/api/v1/automation-pending-tasks/${id}/resolve`, { resolution });
|
||||
|
||||
// Rules - 关键词回复规则 (使用关键词API)
|
||||
type KeywordRowPayload = {
|
||||
/** id 表示标识。 */ id: string;
|
||||
/** keyword 表示关键词。 */ keyword: string;
|
||||
/** reply 表示回复内容。 */ reply: string;
|
||||
/** item_id 表示商品标识。 */ item_id: string;
|
||||
/** type 表示规则类型。 */ type: 'text' | 'image';
|
||||
/** image_url 表示图片地址。 */ image_url: string;
|
||||
};
|
||||
|
||||
// normalizeKeywordRow 归一化关键词规则。
|
||||
const normalizeKeywordRow = (item: any): KeywordRowPayload => ({
|
||||
id: String(item?.id || ''),
|
||||
keyword: item?.keyword || '',
|
||||
reply: item?.reply || '',
|
||||
item_id: item?.item_id || '',
|
||||
type: item?.type === 'image' ? 'image' : 'text',
|
||||
image_url: item?.image_url || '',
|
||||
});
|
||||
|
||||
// getKeywordRowsWithType 读取带类型的关键词规则。
|
||||
const getKeywordRowsWithType = async (cookieId: string): Promise<KeywordRowPayload[]> => {
|
||||
// existing 已有规则,用于当前 API 处理流程。
|
||||
const existing = await get<unknown>(`/api/v1/reply-rules/${cookieId}/typed`);
|
||||
return collectionFrom<KeywordTypedResponse>(existing, ['data', 'items', 'rules']).map(normalizeKeywordRow);
|
||||
};
|
||||
|
||||
// getReplyRules 读取回复规则。
|
||||
export const getReplyRules = async (cookieId?: string): Promise<ReplyRule[]> => {
|
||||
if (!cookieId) return [];
|
||||
// keywords keywords,用于当前 API 处理流程。
|
||||
const keywords = await getKeywordRowsWithType(cookieId);
|
||||
return keywords.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
|
||||
id: item.id,
|
||||
keyword: item.keyword || '',
|
||||
reply_content: item.reply || '',
|
||||
match_type: 'fuzzy' as const,
|
||||
enabled: true,
|
||||
item_id: item.item_id || '',
|
||||
type: item.type === 'image' ? 'image' : 'text',
|
||||
image_url: item.image_url || ''
|
||||
}));
|
||||
}
|
||||
|
||||
// updateReplyRule 更新回复规则。
|
||||
export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string): Promise<OperationResponse> => {
|
||||
// type 规则类型,用于当前 API 处理流程。
|
||||
const type = rule.type || 'text';
|
||||
// payload 请求载荷,用于当前 API 处理流程。
|
||||
const payload = {
|
||||
keyword: rule.keyword || '',
|
||||
reply: type === 'text' ? (rule.reply_content || '') : '',
|
||||
item_id: rule.item_id || '',
|
||||
type,
|
||||
image_url: type === 'image' ? (rule.image_url || '') : '',
|
||||
};
|
||||
return rule.id
|
||||
? put(`/api/v1/reply-rules/${cookieId}/typed/${rule.id}`, payload)
|
||||
: post(`/api/v1/reply-rules/${cookieId}/items`, payload);
|
||||
}
|
||||
|
||||
// deleteReplyRule 删除回复规则。
|
||||
export const deleteReplyRule = async (id: string, cookieId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/reply-rules/${cookieId}/typed/${id}`);
|
||||
}
|
||||
|
||||
|
||||
// Default Reply
|
||||
// getDefaultReplies 读取默认回复列表。
|
||||
export const getDefaultReplies = async (): Promise<Record<string, DefaultReplyResponse>> => {
|
||||
const response = await get<unknown>('/api/v1/default-replies');
|
||||
// replies 是兼容直接映射、data 包裹和 null 的默认回复索引。
|
||||
return objectFrom<Record<string, DefaultReplyResponse>>(response, ['data', 'replies', 'items']) || {};
|
||||
};
|
||||
|
||||
// getDefaultReply 读取默认回复。
|
||||
export const getDefaultReply = async (cookieId: string): Promise<DefaultReply> => {
|
||||
// result 接口响应结果,用于当前 API 处理流程。
|
||||
const response = await get<unknown>(`/api/v1/default-replies/${cookieId}`);
|
||||
// result 是兼容直接默认回复和 data 包裹后的对象。
|
||||
const result = objectFrom<Partial<DefaultReplyResponse>>(response, ['data', 'result']) || {};
|
||||
return {
|
||||
cookie_id: cookieId,
|
||||
enabled: result.enabled || false,
|
||||
reply_content: result.reply_content || '',
|
||||
reply_once: result.reply_once || false,
|
||||
reply_image_url: result.reply_image_url || ''
|
||||
};
|
||||
};
|
||||
|
||||
// updateDefaultReply 更新默认回复。
|
||||
export const updateDefaultReply = async (cookieId: string, data: Partial<DefaultReply>): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/default-replies/${cookieId}`, {
|
||||
enabled: data.enabled ?? false,
|
||||
reply_content: data.reply_content || '',
|
||||
reply_once: data.reply_once ?? false,
|
||||
reply_image_url: data.reply_image_url || ''
|
||||
});
|
||||
};
|
||||
|
||||
// deleteDefaultReply 删除默认回复。
|
||||
export const deleteDefaultReply = async (cookieId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/default-replies/${cookieId}`);
|
||||
};
|
||||
|
||||
// clearDefaultReplyRecords 清理默认回复记录。
|
||||
export const clearDefaultReplyRecords = async (cookieId: string): Promise<OperationResponse> => {
|
||||
return post(`/api/v1/default-replies/${cookieId}/clear-records`, {});
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, Card, DefaultReply, Item, ReplyRule, ShippingRule } from '../../../types';
|
||||
import type { AccountDetail, Card, DefaultReply, Item, ReplyRule, ShippingRule } from '../../../shared/api-contract';
|
||||
import {
|
||||
getAccountDetails,
|
||||
getAutomationIssues,
|
||||
|
||||
@@ -16,7 +16,7 @@ import type {
|
||||
Item,
|
||||
ReplyRule,
|
||||
ShippingRule,
|
||||
} from '../../../types';
|
||||
} from '../../../shared/api-contract';
|
||||
import type { AutomationIssueState, RulesDataOptions, RulesDataResult, RulesTab } from './types';
|
||||
import { isCurrentRequest, nextRequestGeneration } from './interactionState';
|
||||
|
||||
|
||||
Loaded 100 of 305 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user