Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
353daa2eec | ||
|
|
f5064254dc | ||
|
|
d92fb0f4cc | ||
|
|
1426e3ed31 | ||
|
|
17dcd50148 | ||
|
|
29d550473e | ||
|
|
d0de5d77e2 | ||
|
|
b791ba43d7 | ||
|
|
3710317011 | ||
|
|
37e494ae76 | ||
|
|
9de1e024fc | ||
|
|
dab4fb54bf | ||
|
|
3b67ab81ee | ||
|
|
58f91ac77d | ||
|
|
50eca2fca6 | ||
|
|
44f0b5c559 | ||
|
|
3b57a8c4aa | ||
|
|
7b9867cb98 | ||
|
|
7c4a944b43 | ||
|
|
76f4e2e87d | ||
|
|
5675f60e52 | ||
|
|
819cb1175d | ||
|
|
c175d2082a | ||
|
|
5fc32239f6 | ||
|
|
fba0915fd3 | ||
|
|
c3020bde09 | ||
|
|
c1282dfa4e |
No files matched your search
@@ -4,8 +4,8 @@ on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -44,6 +44,9 @@ jobs:
|
||||
- name: 检查架构依赖
|
||||
run: go run ./tools/architecturecheck
|
||||
|
||||
- name: 检查 OpenAPI 路由与规范
|
||||
run: go run ./tools/apicheck
|
||||
|
||||
- name: 运行 go vet
|
||||
run: go vet ./...
|
||||
|
||||
@@ -82,6 +85,9 @@ jobs:
|
||||
- name: 检查 TypeScript 类型
|
||||
run: npm run typecheck --prefix frontend
|
||||
|
||||
- name: 检查 OpenAPI 生成产物
|
||||
run: npm run api:check --prefix frontend
|
||||
|
||||
- name: 运行前端测试
|
||||
run: npm test --prefix frontend
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ name: 构建桌面端安装包
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
|
||||
@@ -3,7 +3,6 @@ name: 构建并发布 Docker 镜像
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
|
||||
@@ -221,6 +221,10 @@ until their recorded phase is completed; agents MUST NOT add new violations.
|
||||
transport adapter boundary.
|
||||
- Route-prefix changes require `frontend/vite.config.ts`, frontend API callers, contract tests and embedded assets
|
||||
to be updated together.
|
||||
- `api/openapi.yaml` is the only contract source for `/api/v1/**` and `/health`; every new versioned operation must
|
||||
update the specification, regenerate `frontend/shared/api-contract/generated/schema.ts`, and add a real handler
|
||||
contract test before a feature can call it. Generated types are read-only, and feature UI models must remain behind
|
||||
their own API adapters.
|
||||
|
||||
## Mandatory React constraints
|
||||
|
||||
@@ -239,6 +243,8 @@ until their recorded phase is completed; agents MUST NOT add new violations.
|
||||
- New or materially changed user flows require behavior tests for success, failure, cancellation, switching and
|
||||
stale responses. Source-string tests are reserved for static architecture rules.
|
||||
- Generated API types are read-only; feature adapters convert transport DTOs to UI models.
|
||||
- Feature code must not import the generated schema directly, restore `transport.ts`, or import legacy
|
||||
`get/post/put/del/postForm`; only the shared contract runtime may call `fetch`.
|
||||
|
||||
## Mandatory database, transaction and multi-dialect constraints
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
GO ?= go
|
||||
GOLANGCI_LINT ?= golangci-lint
|
||||
|
||||
.PHONY: build build-int build-browser-install build-tray test test-server test-server-race test-multidb test-int vet lint architecture cover cover-browser cover-frontend tidy frontend fmt comments check
|
||||
.PHONY: build build-int build-browser-install build-tray test test-server test-server-race test-multidb test-int vet lint architecture api-generate api-check cover cover-browser cover-frontend tidy frontend fmt comments check
|
||||
|
||||
## build: 编译 server(默认,跳过 integration build tag)
|
||||
build:
|
||||
@@ -55,6 +55,19 @@ lint:
|
||||
architecture:
|
||||
$(GO) run ./tools/architecturecheck
|
||||
|
||||
## api-generate: 从 OpenAPI 唯一契约源生成只读 TypeScript transport 类型
|
||||
api-generate:
|
||||
npm run api:generate --prefix frontend
|
||||
|
||||
## api-check: 校验 OpenAPI 规范、版本化路由登记和生成 TypeScript 产物漂移
|
||||
api-check:
|
||||
npm run api:check --prefix frontend
|
||||
$(GO) run ./tools/apicheck
|
||||
$(GO) test ./internal/server -run '^TestOpenAPIRoutesMatchRouter$$' -count=1
|
||||
$(GO) test ./internal/server -run '^TestOpenAPIOperationsHaveContractScenarios$$' -count=1
|
||||
$(GO) test ./internal/server -run '^TestOpenAPISuccessContractCoverage$$' -count=1
|
||||
$(GO) test ./internal/server -run '^(TestOpenAPIPasswordLoginDisabledOperations|TestDownloadItemPublishBatchResultExportsRows|TestChatEventDTOUsesFrontendContract|TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents)$$' -count=1
|
||||
|
||||
## cover: 生成覆盖率报告
|
||||
cover:
|
||||
$(GO) test -coverprofile=cover.out ./... && $(GO) tool cover -func=cover.out | tail -1
|
||||
@@ -85,4 +98,4 @@ comments:
|
||||
node frontend/scripts/check-comments.mjs --mode check --root frontend
|
||||
|
||||
## check: 本地提交前全套检查(fmt + vet + lint + test)
|
||||
check: fmt architecture vet lint test comments
|
||||
check: fmt architecture api-check vet lint test comments
|
||||
@@ -1,7 +1,5 @@
|
||||
# Ydisks闲鱼助手
|
||||
|
||||

|
||||
|
||||
基于 Go 与 React 构建的闲鱼多账号管理、消息回复与自动发货系统
|
||||
|
||||
[](go.mod)
|
||||
@@ -16,9 +14,19 @@
|
||||
在线聊天、账号自动任务、批量铺货、自动化发货、AI、通知和运维流程。
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或
|
||||
> 授权关系。请仅在遵守当地法律法规、闲鱼平台规则及账号授权范围的前提下使用。
|
||||
> 使用自动化能力可能触发平台风控,请自行评估风险并妥善保护账号凭证。
|
||||
> 本项目仅用于个人技术学习研究,**未获得闲鱼/阿里巴巴任何官方授权**。
|
||||
>
|
||||
> 本项目调用闲鱼网页端非公开接口,使用本软件将违反闲鱼用户协议,可能造成闲鱼账号封禁。
|
||||
>
|
||||
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或授权关系。
|
||||
>
|
||||
> 请仅在遵守当地法律法规的前提下使用,所有使用该代码造成的一切后果,全部由使用者自行承担,项目作者不承担任何责任。
|
||||
>
|
||||
> 收到平台下架通知时,本项目会随时删除归档。
|
||||
>
|
||||
> **有账号登录时,不要频繁重启本程序!**
|
||||
>
|
||||
> **每次重启都会向闲鱼申请登录凭证,达到某个频率,即会触发风控。**
|
||||
|
||||
## 项目简介
|
||||
|
||||
@@ -28,7 +36,7 @@ Ydisks闲鱼助手是一个面向闲鱼卖家的自托管管理系统。它将
|
||||
|
||||
项目采用 Go 语言实现闲鱼登录、Cookie 续期、MTOP 请求和 WebSocket 消息链路。
|
||||
扫码登录、人脸验证流程、消息连接、凭证更新和绝大部分业务逻辑均由 Go 客户端完成。
|
||||
使用 Chromium 处理必须依赖浏览器环境的滑块风控。
|
||||
使用 Chromium 处理必须依赖浏览器环境的相关功能。
|
||||
|
||||
### 与 Ydisks 网盘拉新助手协同使用
|
||||
|
||||
@@ -49,7 +57,6 @@ Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名
|
||||
- 付款后发货、评价赠品、超时求评价等自动化流程
|
||||
- 商品与订单同步、单商品发布及支持逐行/默认类目、自动识别和最终兜底的表格批量铺货
|
||||
- 接入 OpenAI 兼容接口实现可控的 AI 客服回复
|
||||
- 账号掉线、风控、续期和发货结果的多渠道通知
|
||||
|
||||
## 功能特性
|
||||
|
||||
@@ -70,8 +77,6 @@ Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名
|
||||
| 安全能力 | 管理端会话、敏感字段 AES-256-GCM 加密、日志脱敏和出站地址校验 |
|
||||
| 容器部署 | PostgreSQL 17、健康检查、持久化卷、GHCR amd64/arm64 多架构镜像 |
|
||||
|
||||
批量铺货的类目优先级为:表格当前行指定类目 > 上传页通过关键词获取的默认类目 > 闲鱼按标题、描述和图片自动识别 > “电子资料”最终兜底。模板类目字段可全部留空;如填写,类目 ID、名称和频道类目 ID 必须同时填写,淘宝类目 ID 按闲鱼响应提供的值填写。
|
||||
|
||||
## 系统架构
|
||||
|
||||
```mermaid
|
||||
@@ -84,7 +89,7 @@ flowchart LR
|
||||
Engine --> MTOP["闲鱼 MTOP"]
|
||||
Engine --> Automation["自动化中心"]
|
||||
Automation --> Notify["通知渠道"]
|
||||
Engine -. "仅指纹与滑块风控" .-> Chromium["Playwright / Chromium"]
|
||||
Engine -. "浏览器能力" .-> Chromium["Playwright / Chromium"]
|
||||
```
|
||||
|
||||
核心职责划分:
|
||||
@@ -94,7 +99,7 @@ flowchart LR
|
||||
- `internal/xianyu`:登录协议、Cookie、MTOP、WebSocket 和消息协议
|
||||
- `internal/engine`:单账号生命周期、消息处理、回复与交付行为
|
||||
- `internal/automation`:发货、评价赠品、求评价和任务调度
|
||||
- `internal/browser`:Chromium 指纹读取与滑块验证
|
||||
- `internal/browser`:Chromium 指纹读取
|
||||
- `internal/db`:多数据库访问、敏感字段加密和嵌入式迁移
|
||||
- `internal/server`:HTTP/SPA transport、管理端鉴权和前端静态资源
|
||||
|
||||
@@ -297,8 +302,7 @@ go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188 -no-browser
|
||||
```
|
||||
|
||||
此模式仍可运行管理后台,但浏览器指纹读取和滑块风控处理不可用,不建议用于需要登录
|
||||
和长期运行账号的生产环境。
|
||||
此模式仍可运行管理后台,但由于缺少UA,无法登陆账号。
|
||||
|
||||
## 初次使用
|
||||
|
||||
@@ -383,7 +387,7 @@ Docker Compose 还支持:
|
||||
| `-playwright-browser-dir` | 空 | Playwright 浏览器缓存目录,会设置为当前进程的 browser 路径 |
|
||||
| `-data-key-file` | 空 | `XIANYU_DATA_KEY` 持久化文件;文件不存在时自动生成 |
|
||||
| `-secure` | `false` | 为管理端 Cookie 添加 `Secure` 属性,HTTPS 部署应启用 |
|
||||
| `-no-browser` | `false` | 禁用 Chromium 指纹读取和滑块处理 |
|
||||
| `-no-browser` | `false` | 禁用 Chromium 指纹读取 |
|
||||
| `-log-level` | 环境变量或系统设置 | 覆盖日志等级 |
|
||||
| `-log-format` | 环境变量或系统设置 | 覆盖日志格式 |
|
||||
| `-v` | `false` | 启用调试日志,等价于未显式配置时使用 debug |
|
||||
@@ -422,7 +426,6 @@ DATABASE_URL="postgres://user:pass@127.0.0.1:5432/xianyu?sslmode=disable" ./xian
|
||||
- **议价策略**:最大折扣比例、最大折扣金额和最多议价轮次
|
||||
- **通知设置**:Bark、钉钉、飞书、企业微信、Telegram、邮件和 Webhook
|
||||
- **日志设置**:日志等级、输出格式和续期日志保留天数
|
||||
- **远程滑块服务**:服务地址、密钥及是否允许传递 Cookie;默认不传递 Cookie
|
||||
- **管理凭据**:管理员用户名、密码和邮箱
|
||||
|
||||
AI Base URL 支持 OpenAI 兼容接口,可连接 OpenAI、通义千问、Ollama、vLLM、
|
||||
@@ -596,7 +599,7 @@ services:
|
||||
│ ├── application/ # 用例编排、事务与补偿
|
||||
│ ├── adapter/ # 业务模块接线层
|
||||
│ ├── automation/ # 自动化中心与调度器
|
||||
│ ├── browser/ # Chromium 指纹和滑块验证
|
||||
│ ├── browser/ # Chromium 指纹验证
|
||||
│ ├── composition/ # 唯一生产组合根
|
||||
│ ├── db/ # 数据访问、加密与迁移
|
||||
│ ├── engine/ # 单账号消息和交付运行时
|
||||
@@ -713,6 +716,7 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
|
||||
- 根据页面二维码在闲鱼 App 完成人脸或安全验证。
|
||||
- 检查服务器时间、时区和外网连接是否正常。
|
||||
- 不要同时在多个实例中运行同一个闲鱼账号,避免凭证相互覆盖。
|
||||
- 若一直提示需要安全验证,请清除账号登录凭证,停用账号。登录闲鱼官方Web版,打开消息页面后,人工通过风控后等待一会儿后再尝试登录。
|
||||
|
||||
### 修改 `XIANYU_DATA_KEY` 后无法读取凭证
|
||||
|
||||
@@ -727,7 +731,7 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
|
||||
- 不要提交 `.env`、数据库文件、Cookie、二维码、日志或浏览器数据目录。
|
||||
- 定期备份 PostgreSQL,并实际验证恢复流程。
|
||||
- 使用版本或 SHA 镜像标签部署生产环境。
|
||||
- 仅向可信的 AI、SMTP、Webhook 和远程滑块服务发送数据。
|
||||
- 仅向可信的 AI、SMTP、Webhook 发送数据。
|
||||
- 发现账号异常时先停用账号,再检查登录审计和续期日志。
|
||||
|
||||
## 贡献
|
||||
@@ -738,7 +742,6 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
|
||||
2. 为协议、数据库和关键业务行为补充测试。
|
||||
3. 运行 `make check` 和前端测试。
|
||||
4. 不要提交真实账号、Cookie、订单、卡密、密钥或其他敏感数据。
|
||||
5. 不要在未说明原因和验证证据的情况下修改风控与滑块行为。
|
||||
|
||||
提交安全问题时,请避免在公开 Issue 中附带真实凭证或用户数据。
|
||||
|
||||
|
||||
+8322
File diff suppressed because it is too large.
Load diff
@@ -26,6 +26,7 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/logging"
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/netguard"
|
||||
appversion "xianyu-go/internal/version"
|
||||
)
|
||||
|
||||
@@ -352,6 +353,13 @@ func openServerInfrastructure(ctx context.Context, startup serverStartupConfig,
|
||||
closeLog()
|
||||
return serverInfrastructure{}, fmt.Errorf("校验或升级数据库敏感字段失败: %w", err)
|
||||
}
|
||||
// outboundPublicOnly 保存用户可配置 HTTP 请求的启动期公网限制快照。
|
||||
if raw, settingErr := store.Settings.Get(ctx, "outbound_http_public_only"); settingErr == nil {
|
||||
netguard.SetDefaultPublicOnly(strings.EqualFold(strings.TrimSpace(raw), "true"))
|
||||
} else {
|
||||
logger.Warn("读取统一 HTTP 出站策略失败,按默认关闭处理", "err", settingErr)
|
||||
netguard.SetDefaultPublicOnly(false)
|
||||
}
|
||||
if !startup.explicitLogLevel {
|
||||
// level、levelErr 分别是数据库保存的日志等级及其读取错误;读取失败时保留进程默认值。
|
||||
if level, levelErr := store.Settings.Get(ctx, "log_level"); levelErr == nil && strings.TrimSpace(level) != "" {
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
- 服务端旧入口继续作为兼容适配层保留,必须复用同一个 handler、鉴权和 DTO,不得复制业务逻辑。
|
||||
- 新增接口必须先进入 `/api/v1/...`,旧路径只有在确认外部调用方为零后才允许删除。
|
||||
- 删除旧路径前必须在本文件记录调用方审计证据、迁移版本和回滚方式,并同步删除对应契约测试。
|
||||
- 兼容旧路径不重复登记 OpenAPI;它们必须复用已登记的 `/api/v1` handler,并由等价路由测试保护。
|
||||
- 任何新版本化 operation 必须先更新 `api/openapi.yaml`、生成只读 schema 并补真实 handler 契约测试,才允许
|
||||
feature adapter 使用;兼容矩阵不能成为字段、路径或 DTO 旁路。
|
||||
|
||||
## API 调用方审计
|
||||
|
||||
|
||||
@@ -57,6 +57,6 @@
|
||||
- 二维码生成、扫码状态查询、状态持久化和验证完成已由版本化路由提供;React 生成、轮询和验证完成调用已迁移,Go/React 契约测试确认新旧入口认证、会话所有权和状态码语义一致,状态响应继续过滤 Cookie 等敏感字段。
|
||||
- 会话密码修改、登录凭证更新、账号删除、密码登录禁用入口、自动化规则/异常处理、订单删除和商品创建已由版本化路由提供;React 对应调用已迁移,Go/React 契约测试确认新旧入口权限、状态码和参数校验语义一致。
|
||||
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
|
||||
- React 的 feature API adapter 已直接使用 `frontend/shared/api-contract/*` 中的具名响应 DTO,并在 adapter 边界完成兼容字段归一;通用请求、错误解析和契约校验位于 `frontend/shared/http/*`。
|
||||
- React 的 feature API adapter 通过 `frontend/shared/api-contract/client.ts` 使用由 `api/openapi.yaml` 生成的路径与响应类型,并在 adapter 边界完成兼容字段归一为 feature-owned UI model;通用请求、错误解析和契约校验位于 shared 契约运行时。
|
||||
- 会话、账号、订单、商品、自动化、设置、卡券、通知、聊天、账号任务、关键词、默认回复、管理员、统计、二维码登录和密码登录版本化入口已可用;旧路径继续保留。
|
||||
- 最终调用方审计确认 React 生产请求、批量结果下载和 Vite 开发代理均不再使用业务旧路径;旧路径仅作为服务端兼容入口保留,后续删除必须遵循调用方、发布日期和回滚条件记录。
|
||||
@@ -137,6 +137,8 @@ refactoring-master-plan.md 定义,本文不声明当前阶段或完成状态
|
||||
- 禁止新增 `value/cookie`、`remark/note` 一类双重字段;
|
||||
- 兼容字段只能在边界 adapter 中归一;
|
||||
- 删除兼容层必须有调用方迁移和契约测试证据。
|
||||
- `/api/v1/**` 与 `/health` 的唯一 HTTP 契约源是 `api/openapi.yaml`;新增 operation 必须同步更新规范、生成
|
||||
TypeScript schema 和真实 handler 响应校验,禁止恢复手写 `transport.ts` 或 DTO 名单门禁。
|
||||
|
||||
## 6. React 边界
|
||||
|
||||
@@ -150,6 +152,8 @@ refactoring-master-plan.md 定义,本文不声明当前阶段或完成状态
|
||||
- 组件不得直接调用 `fetch` 或 `axios`;
|
||||
- 通用 HTTP client 不包含订单、账号等领域归一逻辑;
|
||||
- 生成 API 类型只读,UI model 由 feature adapter 创建;
|
||||
- 生成 schema 只能由 shared 契约层导入,feature、组件和 Hook 不得直接读取;
|
||||
- 原始 `get/post/put/del/postForm` 只能留在旧客户端兼容实现,feature 不得导入或调用;
|
||||
- 禁止通过大型 barrel 文件隐藏实际依赖。
|
||||
|
||||
## 7. 事务与生命周期边界
|
||||
|
||||
@@ -1,233 +1,80 @@
|
||||
# Ydisks 闲鱼助手重构总计划
|
||||
# OpenAPI 契约收口重构总计划
|
||||
|
||||
## 唯一治理规则
|
||||
|
||||
本文是唯一的阶段状态、顺序和验收依据。AGENTS.md 只负责要求读取本文;refactoring-progress.md 只
|
||||
保存最终提交与验收证据;其他架构文档只记录领域约束,不定义阶段状态。
|
||||
历史验收记录不得写入“唯一当前阶段”“下一阶段入口”或“不得提前执行”等阶段指令,避免与本表形成第二个状态源。
|
||||
本文是唯一阶段状态、顺序和验收依据。`refactoring-progress.md` 只保存旧六阶段最终提交与证据,不定义新阶段入口。旧六阶段成果是不可回退的已完成架构基线:应用服务、数据库、生命周期和 React feature 化均不重新实施,既有安全、依赖、注释、兼容和冻结 CAPTCHA 门禁继续有效。
|
||||
|
||||
本重构只有六个正式阶段。旧的十阶段编号、阶段 0、纵向切片、当前切片、分轮迭代、局部完成声明和
|
||||
一个改动一个提交的规则全部失效。阶段是唯一任务、评审和交付单位:一个阶段允许同时修改多个 Go
|
||||
包、多个前端 feature、测试、门禁、文档和嵌入产物;agent 不得拆分子任务、垂直切片、独立 PR 或
|
||||
中间提交。阶段最终提交必须可编译、可启动、可测试并通过全部强制验证。阶段完成前不得创建提交,
|
||||
最终只创建一条中文阶段提交。
|
||||
本计划只有六个正式阶段,严格按 1 -> 2 -> 3 -> 4 -> 5 -> 6 执行。一个阶段是一个任务、一个评审单元和一条最终中文提交;阶段中不得创建中间提交、切片交付、提前更新状态或进入后续阶段。
|
||||
|
||||
禁止无关重命名、全仓格式化、依赖升级、削弱测试或覆盖率、扩大兼容白名单、修改默认 :59188、改变
|
||||
远程首次初始化行为,以及修改冻结 CAPTCHA 文件、测试、参数、调用顺序或规范。
|
||||
## 目标与边界
|
||||
|
||||
## 基础验证层(非正式阶段)
|
||||
唯一 HTTP 契约链路:`OpenAPI 3.1 -> 生成 TypeScript paths/types -> 类型化 HTTP client -> feature adapter -> UI model`。
|
||||
|
||||
完整架构门禁必须在业务迁移前建立,不属于阶段六的末尾补救工作。`tools/architecturecheck` 预先登记阶段二
|
||||
至阶段六的全部规则,并从本文状态表读取唯一“当前阶段”:当前阶段及全部前序规则立即 fail-closed,后续
|
||||
规则保持已定义但暂不阻断。状态表缺失、重复当前阶段或无法解析时,门禁自身失败;阶段六明确完成后
|
||||
即使不再存在“当前阶段”,全量门禁仍永久开启。
|
||||
`api/openapi.yaml` 是 `/api/v1/**` 与 `/health` 的唯一 HTTP 契约源;旧兼容路径不重复登记,继续由兼容矩阵和等价路由测试保护。生成的 `frontend/shared/api-contract/generated/schema.ts` 只读并提交。真实 handler 使用 `kin-openapi` 按同一规范校验。
|
||||
|
||||
门禁目录固定覆盖:Server 组合根与平台旁路、worker 生命周期与根 Context、React feature/契约/网络边界、
|
||||
上层裸数据库与事务泄露、复杂度与超大文件、兼容登记与 Sunset。阶段只负责激活规则并清零真实违规,
|
||||
不得到阶段执行时才临时设计验收逻辑。
|
||||
|
||||
## 目标边界
|
||||
|
||||
cmd 只处理配置、依赖构造、信号和生命周期。internal/server 只处理 HTTP/WebSocket transport、鉴权、
|
||||
中间件、具名 DTO、错误映射和 SPA。应用服务拥有用例、所有权、事务和补偿,不依赖 HTTP、Server、
|
||||
DB 或平台实现。internal/db 独占 SQL、方言、迁移、加密和 repository。React 使用 app -> features ->
|
||||
shared,feature adapter 直接转换领域 DTO 为 feature-owned UI model。
|
||||
契约校验采用非对称规则:OpenAPI 中前端必需字段缺失或类型错误失败;声明的可选字段类型错误失败、缺失允许;后端额外非敏感字段允许,且不会出现在生成的前端类型中。敏感字段泄漏仍由安全门禁和响应测试独立阻断。UI 派生模型、表单状态和兼容归一模型不是 HTTP DTO。对象默认允许额外属性;动态设置、账号通知绑定等动态对象显式声明 `additionalProperties` 值类型。每个 operation 必须有稳定 `operationId`、成功响应、统一错误响应、鉴权元数据和请求参数,不得用无约束 `{}`、`object` 或 `any` 代替已知业务字段。
|
||||
|
||||
## 当前状态
|
||||
|
||||
状态只能是 待验收、当前阶段、待执行、阻塞、已完成;已完成必须绑定最终中文提交和完整命令输出。
|
||||
|
||||
| 阶段 | 状态 | 严格结论 |
|
||||
| --- | --- | --- |
|
||||
| 1. 稳定性、安全和启动生命周期 | 已完成(既有基线) | 已按当前工作树复核原子 data key、同步 Bind、启动回滚、无秘密告警及该阶段命令。六阶段治理建立时这些改动已经存在;禁止为纠正历史提交名重新提交或改写历史。 |
|
||||
| 2. Server 组合根和应用服务迁移 | 已完成 | `internal/composition` 已成为唯一生产组合根;旧 Server 组合根与生命周期反转已删除。Server 仅接收经校验的消费者 Port,阶段二 AST 门禁和完整验收均已通过。最终提交绑定见 `refactoring-progress.md`。 |
|
||||
| 3. 生命周期、Engine 和 Automation 重新验收 | 已完成 | 已完成后台任务 owner/Context/Cancel/Wait 收口、同步凭证更新的调用 Context 传递、浏览器组合根生命周期接入和 AST 生命周期门禁;最终提交与完整证据见 `refactoring-progress.md`。 |
|
||||
| 4. React Feature 化和异步状态修复 | 已完成 | 已完成领域契约直接模块、feature API adapter 边界、统一 ApiError、items 地图迁移、定位取消/超时、批量轮询代次隔离、严格 TypeScript 检查和嵌入产物重建;最终证据见 `refactoring-progress.md`。 |
|
||||
| 5. DB 与事务治理重新验收 | 已完成 | 已以 AST 门禁收束上层裸 SQL、Store.DB 与事务入口,补齐订单/商品 UoW 的提交和回滚证据,并完成 SQLite、MySQL、PostgreSQL 与 dbverify 实测;最终提交绑定见 `refactoring-progress.md`。 |
|
||||
| 6. 全量架构、兼容退场和注释收口 | 已完成 | 最终质量门禁已清零;超大文件和过长函数按业务职责拆分,兼容、依赖方向、注释与复杂度门禁保持 fail-closed。最终提交与完整证据见 `refactoring-progress.md`。 |
|
||||
| 既有架构基线:稳定性、组合根、生命周期、React、DB、质量收口 | 已完成(不可回退) | 历史实现和证据留在 `refactoring-progress.md`,不重做、不改写历史。 |
|
||||
| 1. 契约基础设施与全路由登记 | 已完成 | OpenAPI、生成漂移和真实 Router 双向门禁已建立,未改变业务运行时形状。 |
|
||||
| 2. 类型化客户端与登录账号主链路 | 已完成 | session、system、accounts、QR 风控和永久关闭的 password-login 已迁移并完成真实响应校验。 |
|
||||
| 3. 查询、聊天与订单主链路 | 已完成 | dashboard、实际消费的 admin 摘要、chat、orders、刷新任务和 WebSocket 消息均已迁移并完成真实契约校验。 |
|
||||
| 4. 商品、卡券和文件传输 | 已完成 | items、批量发布、cards 和上传 adapter 已迁移;原生 FormData、取消、重试和批次隔离均保留。 |
|
||||
| 5. 自动化、设置和通知动态契约 | 已完成 | rules、automation、settings、notifications 和账号绑定均通过契约客户端;动态账号键有明确值类型约束。 |
|
||||
| 6. 全量封闭与旧手写契约退场 | 已完成 | 已关闭原始 HTTP client 旁路,删除手写 transport DTO 和名单式门禁;全部 operation 已具备真实成功响应或明确特殊校验证据,契约门禁永久启用。 |
|
||||
|
||||
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。六个正式阶段均已完成,阶段二至阶段六的全部门禁永久保持 fail-closed。
|
||||
## 阶段一:契约基础设施与全路由登记
|
||||
|
||||
## 阶段一:稳定性、安全和启动生命周期
|
||||
建立 `api/openapi.yaml`、固定版本的 `openapi-typescript`、`openapi-fetch`、`kin-openapi`、`make api-generate`、`make api-check` 和 CI 漂移检查。通过 `chi.Walk` 比较真实 Router 与规范,双向覆盖 `/api/v1/**`、`/health` 和动态订单刷新路由。每个 operation 立即登记稳定 ID、成功响应、统一错误响应、鉴权和路径参数;业务成功 schema 在后续阶段逐操作收紧。删除 `frontendDTOContractSpecs` 名单式门禁,保留二维码字段修复和通知摘要敏感字段保护,不改变任何 URL、状态码、包装或 feature 行为。
|
||||
|
||||
范围:data key 使用 O_CREATE|O_EXCL,覆盖竞争、空文件、写失败和读竞争;Bind 先于 worker 和
|
||||
Serve;覆盖重复 Start/Stop、已 Bind 未 Serve、启动回滚;修复 SA1012;非 loopback 未初始化只输出
|
||||
不含秘密的高等级告警并更新部署文档。
|
||||
验收:
|
||||
|
||||
~~~text
|
||||
go test ./cmd/server ./internal/server ./internal/notify -count=1
|
||||
go test -race ./cmd/server ./internal/server ./internal/notify -count=1
|
||||
go vet ./...
|
||||
make lint
|
||||
git diff --check
|
||||
~~~
|
||||
|
||||
既有基线:不追补提交,不改写历史。后续涉及其代码时,必须在所属阶段重新运行相关命令。
|
||||
|
||||
## 阶段二:Server 组合根和应用服务迁移(已完成)
|
||||
|
||||
组合根必须由独立 composition 包或等价独立组合层负责;cmd/server 只构造基础设施并调用它;
|
||||
Server 只接受不可变完成依赖。
|
||||
|
||||
必须完成:
|
||||
- 移出 internal/server/application_services.go 中所有 service、runner、coordinator 和 adapter factory 的生产构造。
|
||||
- 删除 server.NewApplicationServices 业务组合根、Server.ApplicationServices() 和 LifecycleComponents() 生命周期反转。
|
||||
- Server 不得持有或调用 MTOP、长登录、QR 登录、Manager、automation、Notifier、DB、Store、session 或具体平台 implementation。
|
||||
- 订单运行时、聊天发送、批量发布、账号登录、Session 恢复、通知测试发送、聊天已读上报全部通过应用 Port。
|
||||
- architecturecheck 扫描真实生产源码,禁止 Server 调用 service/runner/coordinator 构造函数和通过 adapter factory 间接构造业务服务。
|
||||
- 测试覆盖缺失依赖、正常、越权、失败、取消、补偿、启动回滚和独立关闭。
|
||||
|
||||
### 执行形态(对后续 agent 的硬性指导)
|
||||
|
||||
1. 新建独立组合层(建议 `internal/composition`);它是唯一允许同时导入 `internal/application`、
|
||||
`internal/adapter`、`internal/account`、`internal/automation`、`internal/browser`、`internal/notify`
|
||||
与平台依赖的生产装配位置。`cmd/server/main.go` 只构造基础设施、调用组合层、登记其返回的生命周期
|
||||
组件并启动 HTTP Server。
|
||||
2. 将 `internal/server/application_services.go` 的构造函数、`ApplicationServiceDependencies`、生命周期
|
||||
组件生成和 callback 闭包移到组合层及对应的应用/adapter 包。完成后删除该文件,而不是改名保留;
|
||||
`internal/server` 不得再出现 `New*Service`、`New*Runner`、`New*Coordinator` 或 adapter factory 调用。
|
||||
3. `server.Dependencies` 只能包含 HTTP 所需的认证、日志、静态资源、健康检查与由 transport 消费者定义的
|
||||
最小应用 Port。它不得引用 `adapter` 的平台客户端接口、`account.Manager`、`automation.Center`、
|
||||
`notify.Notifier`、`chat.Service`、`db.Store`、`sql.DB` 或 `sql.Tx`。`PlatformPort`、`mtopClient`、
|
||||
`longLoginClient`、`qrLoginService`、`sessionRecoveryCallback` 与测试专用可变平台 Port 一并删除或迁至
|
||||
应用/adapter 测试。
|
||||
4. 按用例而非基础设施对象迁移 handler:二维码登录、账号登录与长登录、Cookie/session 恢复、订单运行时、
|
||||
聊天发送和已读上报、通知测试发送、商品批量发布分别接收消费者定义的应用 Port。handler 只做 DTO
|
||||
解析、当前用户提取、调用、错误到 HTTP 的映射;不得传递 `Server` callback 给 adapter。
|
||||
5. 组合层返回不可变的 `server.Dependencies` 和独立 `[]lifecycle.NamedComponent`。`cmd/server` 直接向
|
||||
`lifecycle.Coordinator` 登记该列表;禁止从 Server 或 Server 持有的服务集合反向读取生命周期组件。
|
||||
6. 重写 `tools/architecturecheck` 为 fail-closed AST 扫描,并增加真实仓库扫描和正反例测试:扫描全部
|
||||
非测试 `internal/server/**/*.go` 与 `cmd/server/**/*.go`,拒绝上述类型、字段、构造调用、factory 调用、
|
||||
Server callback、service locator 及测试专用 setter 的生产使用。现有仅按少量函数名匹配的检查不能作为
|
||||
阶段完成证据。
|
||||
7. 所有现有 Server 测试随用例归属迁移:transport 测试只替换应用 Port fake;业务、平台、恢复和 worker
|
||||
测试进入 application/adapter。为组合层补齐缺失依赖、构造失败、启动回滚和关闭顺序测试。不得因为迁移
|
||||
删除现有错误路径、越权、取消、租约或晚到结果断言。
|
||||
8. 阶段二门禁在迁移开始时即启用,且没有临时白名单:`tools/architecturecheck` 必须拒绝
|
||||
`application_services.go`、Server/cmd 中的 adapter 或业务运行时依赖、Server 平台 Port、组合根 API、
|
||||
生命周期反转、应用/adapter 构造链,以及缺失或未被 `cmd/server` 调用的 `internal/composition`。阶段内
|
||||
门禁失败表示未完成迁移,不得降级为告警;最终提交前必须归零。
|
||||
|
||||
~~~text
|
||||
go test ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||
go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||
```text
|
||||
make api-check
|
||||
go run ./tools/architecturecheck
|
||||
go vet ./...
|
||||
make lint
|
||||
make comments
|
||||
git diff --check
|
||||
~~~
|
||||
|
||||
最终提交:阶段二:完成 Server 组合根和应用服务迁移。
|
||||
|
||||
完成结论:生产装配已迁入 `internal/composition` 与其 `runtime` 子层,`cmd/server` 只构造基础设施并调用
|
||||
组合层;`internal/server` 不再构造业务服务、runner、coordinator 或平台实现,也不再反向返还生命周期组件。
|
||||
Server 的应用依赖由消费者定义的不可变 Port 容器承载,构造期缺失任一必需 Port 即失败。完整原始验收输出、
|
||||
冻结 CAPTCHA 差异检查和最终提交绑定只记录在 `refactoring-progress.md`。
|
||||
|
||||
## 阶段三:生命周期、Engine 和 Automation 重新验收(已完成)
|
||||
|
||||
明确每个 worker 的 owner、Context、Cancel、Wait/Join;cmd 独占协调器;Server Stop 只收束 HTTP;
|
||||
覆盖启动失败、取消、超时、重复关闭、晚到结果和关闭顺序;可在本阶段修复 Engine/Automation 状态问题,
|
||||
但不得改动冻结 CAPTCHA。
|
||||
|
||||
~~~text
|
||||
go test ./... -count=1
|
||||
go test -race ./internal/server ./internal/engine ./internal/automation ./internal/renewal
|
||||
RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
|
||||
make comments
|
||||
go run ./tools/architecturecheck
|
||||
~~~
|
||||
|
||||
最终提交:阶段三:完成生命周期、Engine 和 Automation 重新验收。
|
||||
|
||||
## 阶段四:React Feature 化和异步状态修复(已完成)
|
||||
|
||||
这是一个完整前端阶段,不拆 HTTP 错误、契约、地图、轮询或构建交付:
|
||||
- ApiError 保留 status、code、message、request_id、details、payload;JSON/FormData 共用错误解析。
|
||||
- shared/api-contract/index.ts 拆为 session、accounts、items、orders、automation、notifications、settings、chat、cards、admin、common 直接模块;feature adapter 直接导入领域契约并输出 UI model。
|
||||
- 地图物理迁入 items;locateForPublish 等待定位和搜索;每次请求 AbortController + generation + timeout,旧响应不得写回。
|
||||
- pending、running、canceling 统一视为进行中;每个轮询 effect 独立取消;覆盖重启、关闭重开、晚到响应、取消和卸载。
|
||||
- 清理未使用符号并开启 noUnusedLocals/noUnusedParameters;Vite 重建 internal/webui/static。
|
||||
|
||||
~~~text
|
||||
npm test --prefix frontend
|
||||
go test ./internal/server -count=1
|
||||
npm run typecheck --prefix frontend
|
||||
npm run comments:check --prefix frontend
|
||||
npm run build --prefix frontend
|
||||
make cover-frontend
|
||||
git diff --check
|
||||
~~~
|
||||
|
||||
最终提交:阶段四:完成 React Feature 化和异步状态修复。
|
||||
|
||||
## 阶段五:DB 与事务治理重新验收(已完成)
|
||||
|
||||
清除上层 Store.DB、sql.DB、sql.Tx 和 row model 泄露;跨 repository 原子操作使用 Unit of Work;验证
|
||||
claim、lease、取消、重试、不确定远程结果和本地补偿;补齐 SQLite 并发和事务测试,并运行 MySQL、
|
||||
PostgreSQL、cmd/dbverify。任何发现的 repository、迁移或补偿缺陷必须在本阶段同一提交中完成。
|
||||
|
||||
~~~text
|
||||
go test ./internal/db ./internal/application/... ./internal/adapter -count=1
|
||||
go test -race ./internal/db ./internal/application/... ./internal/adapter -count=1
|
||||
TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb
|
||||
go run ./cmd/dbverify "$TEST_MYSQL_URL"
|
||||
go run ./cmd/dbverify "$TEST_POSTGRES_URL"
|
||||
git diff --check
|
||||
~~~
|
||||
|
||||
最终提交:阶段五:完成数据库与事务治理重新验收。
|
||||
|
||||
完成结论:数据库门禁已改为 AST/import fail-closed 扫描,阻断上层 `database/sql`、`Store.DB` 与
|
||||
`Begin`/`BeginTx` 裸事务旁路;订单与商品写入 UoW 已有 SQLite 原子提交和回滚测试。SQLite、MySQL、
|
||||
PostgreSQL 多方言回归及两个 `cmd/dbverify` 均已实际通过,完整命令输出和提交绑定记录在
|
||||
`refactoring-progress.md`。
|
||||
|
||||
## 阶段六:全量架构、兼容退场和注释收口(已完成)
|
||||
|
||||
门禁框架和全部阶段规则已经前置建立,本阶段不得重新发明或补写基础规则。本阶段激活最终质量门禁,
|
||||
处理此前各阶段持续开启的全部边界,并清零 service locator、动态 import、前端依赖方向、根级 services
|
||||
旁路、模板注释、复杂度和超大文件违规。兼容入口只在遥测、Sunset、调用方迁移和契约测试齐备后删除;
|
||||
不得扩大 baseline、增加白名单或跳过测试。
|
||||
|
||||
~~~text
|
||||
go test ./... -count=1
|
||||
go vet ./...
|
||||
make lint
|
||||
make comments
|
||||
go run ./tools/architecturecheck
|
||||
go test -race ./internal/server ./internal/engine ./internal/automation
|
||||
npm test --prefix frontend
|
||||
npm run typecheck --prefix frontend
|
||||
npm run comments:check --prefix frontend
|
||||
make comments
|
||||
npm run build --prefix frontend
|
||||
make cover
|
||||
make cover-frontend
|
||||
git diff --check
|
||||
~~~
|
||||
```
|
||||
|
||||
适用时还运行浏览器集成、MySQL/PostgreSQL 和两个 cmd/dbverify 命令。最终提交:阶段六:完成全量架构、
|
||||
兼容退场和注释收口。
|
||||
最终提交:`阶段一:建立 OpenAPI 单一契约源与全路由门禁`。
|
||||
|
||||
完成结论:质量门禁已在不新增 architecturecheck/source 架构白名单、baseline 或忽略源目录的前提下清零。生成覆盖率产物的 Git 忽略规则不属于架构门禁豁免。组合根、adapter、browser
|
||||
生命周期、DB repository、Engine、通知、续期、Server DTO、二维码、协议和门禁源码均按业务职责拆分;
|
||||
受保护的 CAPTCHA 文件和规范未改动。完整原始验收输出、覆盖率、浏览器集成与多数据库环境例外记录在
|
||||
`refactoring-progress.md`。
|
||||
## 阶段二:类型化客户端与登录账号主链路
|
||||
|
||||
阶段六完成后的窄范围缺陷修复仍须保持全部门禁永久启用,不得把阶段状态回退为阶段五或创建新的阶段入口;
|
||||
修复范围与本次验收证据只追加到 `refactoring-progress.md` 的阶段六记录。
|
||||
把 Cookie、超时、外部 AbortSignal、401 合并登出、统一 ApiError 和 FormData 行为封装进类型化客户端运行时,迁移 session、system、accounts、QR 风控及永久关闭的 password-login。adapter 继续输出 UI model,生成类型不得直接进入 React state 或 props;补齐成功、未认证、越权、未找到、风控状态和敏感字段不泄漏的真实响应校验。冻结 CAPTCHA 文件、选择器、时序、Cookie 合并和浏览器调用顺序完全不变。
|
||||
|
||||
最终提交:`阶段二:迁移登录账号与风控接口到生成契约`。
|
||||
|
||||
## 阶段三:查询、聊天与订单主链路
|
||||
|
||||
迁移 dashboard、admin、chat、orders 查询和订单刷新任务。WebSocket 握手登记为 HTTP operation,消息体使用 OpenAPI component schema;聊天 adapter 保留唯一原生 WebSocket 实现。保留分页、游标、订单状态、旧包装归一化和晚到响应隔离,覆盖刷新成功、失败、取消、超时及消息字段类型。
|
||||
|
||||
最终提交:`阶段三:迁移查询聊天与订单接口到生成契约`。
|
||||
|
||||
## 阶段四:商品、卡券和文件传输
|
||||
|
||||
迁移 items、批量发布、cards、表格和图片上传、CSV 下载。OpenAPI 明确 multipart、二进制响应、Content-Disposition 和长请求超时;继续使用 FormData,保留批次代次隔离、取消、重试和不确定远端结果。覆盖格式错误、部分成功、取消、重试、CSV 和客户端取消。
|
||||
|
||||
最终提交:`阶段四:迁移商品卡券与文件接口到生成契约`。
|
||||
|
||||
## 阶段五:自动化、设置和通知动态契约
|
||||
|
||||
迁移 rules、automation、settings、notifications 和账号通知绑定。动态设置与按账号 ID 的动态键使用受约束 additionalProperties;通知摘要不返回 SMTP 密码、Token 或渠道秘密配置,编辑器不从摘要 DTO 恢复秘密。覆盖动态键类型、敏感配置三态变更、渠道别名归一、自动化问题和统一错误响应。
|
||||
|
||||
最终提交:`阶段五:迁移自动化设置与通知动态契约`。
|
||||
|
||||
## 阶段六:全量封闭与旧手写契约退场
|
||||
|
||||
禁止 feature、组件和 Hook 导入原始 `get/post/put/del/postForm`,只有共享契约客户端运行时可调用 fetch。删除手写 `transport.ts` 和废弃 DTO;门禁从 OpenAPI 自动发现 operation、生成类型和真实契约测试覆盖,不保留 DTO 名单、路径白名单或可扩展 baseline。每个 operation 必须有真实成功响应,或属于明确的 WebSocket/二进制特殊校验。更新 AGENTS、依赖规则、兼容矩阵和进度证据;新接口必须先改 OpenAPI、生成代码和服务端契约测试才能被前端使用。
|
||||
|
||||
最终验收:`make check`、`go test ./... -count=1`、Server race、全部前端测试、`make cover`、`make cover-frontend`、嵌入前端构建及二维码/浏览器回归。最终提交:`阶段六:完成生成契约迁移并永久关闭旁路`。
|
||||
|
||||
## 执行纪律
|
||||
|
||||
1. 开始一个阶段前,只允许读取总计划状态表并审查当前工作树;不得根据旧阶段编号或已落地代码跳阶段。
|
||||
2. 阶段进行期间不创建提交、不更新阶段状态、不写局部完成记录,也不向后续阶段交付任何实现。
|
||||
3. 阶段最终验收失败时,状态仍是当前阶段;修复全部失败项后重新执行完整命令,不得只重跑失败命令。
|
||||
4. 仅在全部命令成功后,按一次操作更新状态表、验收记录、完成证据和下一阶段入口,再创建唯一中文提交。
|
||||
5. 已存在的正确实现只能作为后续阶段的输入;不能单独改变正式阶段状态,也不得被回滚、清理或拆分重做。
|
||||
|
||||
## 门禁激活规则
|
||||
|
||||
1. 全部阶段规则在基础验证层预先写入自动门禁并具备正反例测试;每个阶段开始时只激活对应规则,之后才允许迁移生产代码。
|
||||
2. 当前阶段门禁必须 fail-closed。阶段内出现违规是未完成工作的可见清单,不得通过白名单、baseline、忽略目录、字符串规避、反射、动态 import 或降低严重级别使其通过。
|
||||
3. 前序阶段已完成的门禁继续保持启用。后续阶段专有门禁只能在其成为当前阶段时启用,避免以尚未执行的设计阻断当前阶段;但任何全局安全、冻结 CAPTCHA、依赖方向、测试和注释规则始终生效。
|
||||
4. 阶段最终验收只接受“当前阶段及全部既有门禁均为零违规”的完整输出。门禁失败时不得更新阶段状态、完成证据或创建提交。
|
||||
阶段最终验收失败时状态仍为当前阶段,修复后重跑完整命令;只有全部命令成功后才一次更新状态、证据和下一阶段入口并创建最终中文提交。六个阶段现已全部完成,后续不再开启新阶段入口。不得扩大白名单、baseline、忽略路径或 warning-only 旁路;后续缺陷修复保持全部已启用门禁永久有效。
|
||||
@@ -3,6 +3,65 @@
|
||||
本文件只记录已经完成阶段的最终提交与验收证据。唯一阶段状态和顺序由
|
||||
`refactoring-master-plan.md` 定义;阶段内工作、临时提交、切片和局部成功一律不记录。
|
||||
|
||||
## OpenAPI 阶段二:类型化客户端与登录账号主链路
|
||||
|
||||
- 最终提交绑定:`阶段二:迁移登录账号与风控接口到生成契约`。
|
||||
- 交付范围:以 `openapi-fetch` 和生成 `paths/types` 为唯一新增请求运行时,保留 Cookie、默认超时、外部
|
||||
AbortSignal、取消/超时错误、401 合并登出、ApiError 和 JSON/FormData 兼容行为。session、accounts、QR
|
||||
风控、system 设置与 AI 模型探测已迁移;账户 adapter 仍输出既有 UI model,生成 transport 类型未进入
|
||||
React state 或组件 props。密码登录的三个永久关闭 operation 保留 501 错误契约,未触碰冻结 CAPTCHA 调用链。
|
||||
- OpenAPI 收紧:账户运行状态、聚合设置、长期登录、自动确认、备注、暂停时长、资料刷新、登录资料和系统
|
||||
设置均使用具名请求/响应 schema;动态系统键限制为字符串、数值或布尔值,敏感设置使用 retain/replace/clear
|
||||
三态命令。后端额外非敏感字段仍按非对称规则允许,账号与系统响应测试独立阻断 Cookie、密码、SMTP 密码
|
||||
和 AI 密钥泄漏。
|
||||
|
||||
### 强制验收原始输出
|
||||
|
||||
```text
|
||||
$ make api-check
|
||||
api-check: 通过;OpenAPI 生成漂移检查和 chi 路由双向覆盖通过。
|
||||
|
||||
$ go run ./tools/architecturecheck
|
||||
architecturecheck: 通过
|
||||
|
||||
$ go test ./internal/server -run '^TestOpenAPI(AccountAndSystem|SessionAndQR)Responses$' -count=1
|
||||
PASS
|
||||
|
||||
$ go test ./... -count=1
|
||||
所有 Go 测试包通过。
|
||||
|
||||
$ go vet ./...
|
||||
(无输出,退出码 0)
|
||||
|
||||
$ make lint
|
||||
golangci-lint run ./...
|
||||
0 issues.
|
||||
|
||||
$ npm test --prefix frontend
|
||||
Test Files 67 passed (67)
|
||||
Tests 405 passed (405)
|
||||
|
||||
$ npm run typecheck --prefix frontend
|
||||
(无输出,退出码 0)
|
||||
|
||||
$ npm run build --prefix frontend
|
||||
vite 构建成功,嵌入前端产物已重建。
|
||||
|
||||
$ make comments
|
||||
commentlint: 通过(Go 与 TypeScript/TSX 均无缺少中文注释或模板化注释)
|
||||
|
||||
$ git diff --check
|
||||
(无输出,退出码 0)
|
||||
```
|
||||
|
||||
### 验收边界
|
||||
|
||||
- 覆盖率:本阶段未修改覆盖率目标,未运行覆盖率命令。
|
||||
- 浏览器:未使用 `RUN_BROWSER_INTEGRATION=1`;未修改 `internal/browser` 或冻结 CAPTCHA 文件。
|
||||
- 外部服务:长期登录成功响应依赖真实平台 `returnValue`,本地契约测试验证其 502 统一错误 envelope;未运行真实账号、
|
||||
MySQL 或 PostgreSQL。
|
||||
- 生成物:生成的 `frontend/shared/api-contract/generated/schema.ts` 与新的嵌入前端构建产物随阶段提交,未手工修改生成文件。
|
||||
|
||||
## 阶段二:Server 组合根和应用服务迁移
|
||||
|
||||
- 最终提交绑定:本文件随最终提交 `阶段二:完成 Server 组合根和应用服务迁移` 一并进入 `HEAD`。
|
||||
@@ -340,3 +399,82 @@ $ git diff --check
|
||||
```
|
||||
|
||||
- 外部环境:2026-08-19 使用 Docker 29.4.0 临时启动 `mysql:8` 与 `postgres:17`,均绑定到本机回环地址并通过就绪检查;真实 Chromium 集成、MySQL/PostgreSQL 多方言回归和两个 `cmd/dbverify` 均已执行且通过。多数据库测试创建并清理独立 `xytest_*` 数据库,验收结束后已删除两个临时容器。未执行真实账号登录或外部平台调用。`cover.out`、`cover-browser.out` 和 `frontend/coverage/` 是生成验证产物,未纳入提交。
|
||||
|
||||
### 2026-08-19 阶段六二维码风控状态 DTO 完整性修复
|
||||
|
||||
- 交付范围:`publicQRStatus` 将底层二维码会话已生成的 `face_qr_url` 和 `verification_screenshot` 显式映射到具名 HTTP DTO;前端共享二维码状态契约同步声明这两个展示字段,账号 feature 的轮询类型经自身 API adapter 派生,避免共享 transport DTO 与 feature 类型漂移。
|
||||
- 敏感数据边界:未重新暴露 `cookies`、`cookie_snapshot`、`unb` 或 `verification_url`。其中验证链接不属于 UI 消费字段,且既有前端契约明确禁止渲染;人脸二维码优先展示,截图只作为兜底。
|
||||
- 回归保护:服务端契约测试同时断言二维码和截图透传、Cookie 脱敏;前端轮询与 Hook 测试仅使用当前公开状态字段;版本化与兼容路由继续复用同一 handler。
|
||||
- 冻结边界:未修改 `internal/browser/slider.go`、`token_captcha*.go`、其测试或冻结规范。
|
||||
|
||||
### 本次验收
|
||||
|
||||
```text
|
||||
$ go test ./internal/server ./internal/xianyu/qrlogin -count=1
|
||||
ok xianyu-go/internal/server
|
||||
ok xianyu-go/internal/xianyu/qrlogin
|
||||
|
||||
$ npm test --prefix frontend -- --run
|
||||
Test Files 67 passed (67)
|
||||
Tests 405 passed (405)
|
||||
|
||||
$ npm run typecheck --prefix frontend
|
||||
(无输出,退出码 0)
|
||||
|
||||
$ npm run comments:check --prefix frontend && make comments
|
||||
Go/前端 commentlint 均通过。
|
||||
|
||||
$ npm run build --prefix frontend
|
||||
✓ built in 2.76s;已重建 internal/webui/static。
|
||||
|
||||
$ go run ./tools/architecturecheck && git diff --check
|
||||
architecturecheck: 通过;git diff --check 无输出。
|
||||
```
|
||||
|
||||
### 2026-08-19 阶段六前后端 DTO 字段完整性门禁
|
||||
|
||||
- 审计范围:共享 `frontend/shared/api-contract/transport.ts` 的全部导出对象 DTO,以及每个 `frontend/app/features/*/api.ts` 中的响应形态 DTO;健康检查 `BuildInfo` 也显式登记。门禁要求每个 DTO 都在 `frontendDTOContractSpecs` 登记,直接 HTTP DTO 的每个顶层字段必须在 `internal/server` 对应具名结构体中以 JSON 标签提供。
|
||||
- 解析边界:门禁会展开 TypeScript `extends` 字段和 Go 匿名嵌入 DTO 字段,避免订单详情等兼容顶层字段产生误报;嵌套对象字段单独属于其行 DTO,不被错误归入外层响应。动态键、feature 归一化和脱敏模型必须逐项写明理由,不能静默跳过。
|
||||
- 修复结果:二维码风控状态已补齐 `verification_screenshot` 和 `face_qr_url`;删除卡券时间字段、账号 AI 模型/密钥字段、通知渠道配置与时间字段等服务端从未提供且前端不消费的历史契约。通知渠道列表继续不返回配置,避免 SMTP 等秘密穿透摘要 DTO;编辑器用空配置初始化。
|
||||
- 回归保护:新增真实临时仓库夹具测试,确认遗漏后端字段会触发门禁;新增匿名嵌入解析测试。冻结滑块验证码实现及其调用语义未修改。
|
||||
|
||||
### 2026-08-20 OpenAPI 契约阶段三:查询、聊天与订单主链路
|
||||
|
||||
- 交付范围:dashboard、订单分析、有效订单、订单分页/详情/更新/删除、异步刷新任务、聊天会话/消息/已读/图片/文本与管理员用户、账号、任务摘要均通过生成的 `/api/v1` operation 调用;UI 继续只消费 feature adapter 输出的派生模型。
|
||||
- WebSocket:`/api/v1/chat/ws` 以 `x-websocket-message-schema` 引用 `ChatWebSocketEvent`。服务端实际 `ready` 和聊天事件 DTO 由同一 OpenAPI component 校验;原生 WebSocket 仍只由聊天通知 owner 使用。
|
||||
- 契约修正:订单刷新项的 `soft_deleted` 由历史错误的整数收紧为真实 handler 输出的布尔值;管理员账号摘要 schema 不包含 Cookie、密码或其他凭证字段。
|
||||
- 验收:`make api-check`、`go run ./tools/architecturecheck`、`go test ./internal/server -count=1`、`npm run typecheck --prefix frontend`、`npm test --prefix frontend`、`make comments` 与 `git diff --check` 均通过。未修改冻结 CAPTCHA 实现,未执行真实账号或外部平台调用。
|
||||
|
||||
### 2026-08-20 OpenAPI 契约阶段四:商品、卡券和文件传输
|
||||
|
||||
- 交付范围:items、发布批次、卡券和表格上传全部改由 feature adapter 通过生成 operation 发起;FormData 在共享运行时按 multipart Content-Type 原样重建,未引入 Base64。
|
||||
- 回归保护:真实 Router 测试覆盖商品、卡券列表的成功和未认证响应,以及卡券文件上传的格式错误 envelope;原有批次取消、重试、代次隔离和 CSV 下载行为保持不变。
|
||||
|
||||
### 2026-08-20 OpenAPI 契约阶段五:自动化、设置和通知动态契约
|
||||
|
||||
- 交付范围:自动化规则、回复规则、默认回复、账号计划任务、账号 AI 设置、系统设置与通知渠道/绑定均通过生成 operation 访问;UI 归一化和秘密表单状态仍留在 feature adapter。
|
||||
- 动态值:`NotificationBindingsByAccount` 使用 `additionalProperties` 限定每个账号键对应 `NotificationBinding[]`;通知渠道摘要不返回 SMTP 密码、Token 或完整秘密配置。
|
||||
- 回归保护:真实 Router 响应测试验证渠道列表与动态账号绑定映射;`make api-check`、architecturecheck、前端 typecheck/tests 与注释门禁通过。
|
||||
|
||||
### 2026-08-20 OpenAPI 契约阶段六:全量封闭与旧手写契约退场
|
||||
|
||||
- 最终提交绑定:`阶段六:完成生成契约迁移并永久关闭旁路`。
|
||||
- 交付范围:删除 `frontend/shared/api-contract/transport.ts`;原有 UI 派生模型、表单模型与兼容归一模型按 accounts、cards、chat、dashboard、items、notifications、orders、rules、session、settings 迁入各自 feature。共享领域契约模块只透明别名导出 `api/openapi.yaml` 生成 schema,feature adapter 保持唯一响应归一化边界。
|
||||
- 永久门禁:architecturecheck 阶段六会拒绝恢复 `transport.ts`、任何 production import/re-export 的 `transport` 路径,以及 feature、组件或 Hook 绕过 shared 契约层直接导入生成 schema;阶段四门禁继续拒绝旧 `get/post/put/del/postForm`。此规则不使用 DTO 名单、路径白名单、baseline 或 warning-only 例外。
|
||||
- 兼容与安全:旧路由继续复用已登记的版本化 handler,不在 OpenAPI 重复登记;允许未声明的非敏感额外响应字段不改变生成类型,Cookie、Token、密码、SMTP 密钥和加密 metadata 仍由既有安全响应测试独立阻断。未修改冻结 CAPTCHA 实现、选择器、时序或浏览器调用顺序,也未执行真实账号调用。
|
||||
- 验收:`make api-check`、`go test ./tools/architecturecheck -count=1`、`go run ./tools/architecturecheck`、`npm run typecheck --prefix frontend`、`npm test --prefix frontend`(67 files、405 tests)、`make comments`、前端嵌入构建、`make check`、`go test ./... -count=1`、`make test-server-race`、`make cover`(Go statements 65.8%)、`make cover-frontend`(V8 statements 80.21%、lines 82.43%)和 `make cover-browser`(`RUN_BROWSER_INTEGRATION=1`,browser statements 64.1%)均通过。冻结浏览器普通单元测试也已通过;未执行真实账号或外部平台调用。覆盖率产物不纳入提交。
|
||||
|
||||
### 2026-08-20 阶段六 operation 自动覆盖门禁补强
|
||||
|
||||
- 门禁实现:新增 `internal/server/openapi_operation_coverage_test.go`,从 `api/openapi.yaml` 自动枚举全部 operationId、路径、方法、必需参数和请求体,直接调用真实 `chi` Router,并用 `kin-openapi` 校验响应状态、Content-Type 和 JSON schema;不维护 DTO、路径或 operation 名单。
|
||||
- 契约修正:补齐通知不确定 outbox、自动化问题与规则、默认回复、商品回复、AI 设置、用户设置以及批量发布响应的具名 schema;动态对象使用受约束 `additionalProperties`,批量发布请求与成功响应同步登记。
|
||||
- 门禁接入:`make api-check` 现在同时执行路由双向覆盖和 operation 自动响应覆盖。生成 schema 仍由临时目录逐字节比较,后端额外非敏感字段不改变生成类型,敏感字段继续由独立安全测试阻断。
|
||||
- 验收:自动 operation 场景覆盖 137 个 operation;`make api-check`、`go test ./internal/server -run '^TestOpenAPIOperationsHaveContractScenarios$' -count=1` 和 `go test ./internal/server -count=1` 通过。未修改冻结 CAPTCHA 实现或真实账号调用。
|
||||
|
||||
### 2026-08-20 阶段六 operation 成功覆盖最终收口
|
||||
|
||||
- 完成范围:新增真实 Router 成功场景覆盖初始化、长登录、AI 模型、卡券上传、聊天读写/图片、商品同步/发布、批次、自动化、通知和账号任务等此前未触达的 operation;覆盖由 OpenAPI operationId 自动发现,不维护 DTO、路径或场景名单。
|
||||
- 契约语义:`kin-openapi` 对真实响应执行状态码、Content-Type 和 JSON schema 校验;必需字段缺失或类型错误、声明字段类型错误、错误状态码和媒体类型都会失败;未声明的非敏感额外字段允许且不会进入生成 TypeScript 类型。敏感字段仍由独立响应安全测试阻断。
|
||||
- 门禁结果:`make api-check`、`go run ./tools/architecturecheck`、`make comments`、`git diff --check`、前端 typecheck、前端 405 项测试和生产构建全部通过;`make check` 与 `go test ./... -count=1` 全部通过,Server race 通过。
|
||||
- 覆盖率:`make cover` Go statements 66.2%;`make cover-frontend` V8 statements 80.2%、lines 82.43%。覆盖率文件和前端覆盖率目录均为生成产物,未纳入提交。
|
||||
- 浏览器与外部环境:冻结 CAPTCHA 普通单元测试随全量 Go 测试通过;本次未执行真实账号或外部平台调用,未修改冻结浏览器实现。浏览器真实集成和多数据库证据继续沿用本文件此前已记录的通过结果。
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 379 KiB After Width: | Height: | Size: 450 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 473 KiB After Width: | Height: | Size: 504 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 728 KiB After Width: | Height: | Size: 686 KiB |
@@ -6,6 +6,14 @@
|
||||
|
||||
本文记录 `internal/browser` 中当前滑块认证的完整行为契约。它是维护边界,不是待办方案。后续任务即使涉及登录、Cookie、浏览器自动化、风控恢复或代码清理,也必须保持本文行为逐项不变。
|
||||
|
||||
## 本次 API 发货 Feature 的远程服务网络补充
|
||||
|
||||
本次用户明确授权仅调整远程滑块服务的网络准入:远程滑块服务请求现在使用统一的用户配置 HTTP 出站策略。系统设置
|
||||
`outbound_http_public_only` 默认关闭;关闭时允许内网 HTTP(S) 地址,但仍限制协议、重定向次数和响应大小;开启时会在 DNS
|
||||
解析和每次重定向连接前拒绝回环、私网、链路本地、保留地址及元数据地址。该开关保存后立即生效。
|
||||
|
||||
这项补充不改变滑块选择器、轨迹、拖动距离、重试顺序、Cookie 合并、成功判定、本地浏览器回退或日志语义。除网络目标校验外,本文其余冻结条款继续优先适用。
|
||||
|
||||
## 1. 保护范围
|
||||
|
||||
以下文件为直接保护对象:
|
||||
|
||||
@@ -19,10 +19,16 @@
|
||||
| 文本 | 固定说明、链接 | 填写文本内容。 |
|
||||
| 批量卡密(`data`) | 一次性兑换码、序列号 | 每行一个卡密;发货会按库存消费。 |
|
||||
| 图片 | 固定图片资源 | 填写公开可访问的图片 URL。 |
|
||||
| API | 外部发码接口 | 填写 URL、GET/POST、超时、请求头和参数;先用无敏感测试数据验证。 |
|
||||
| API | 外部发码接口 | 填写 URL、GET/POST、超时、请求头、参数和响应路径;先用无敏感测试数据验证。 |
|
||||
|
||||
通用字段包括名称、描述、启用状态和默认延时秒数。保存后复制“卡密组 ID”;它是自动化规则和批量铺货表格引用库存的唯一标识。
|
||||
|
||||
API 卡支持 `{order_id}`、`{item_id}`、`{buyer_id}`、`{chat_id}`、`{account_id}`、`{cookie_id}`、`{spec_name}`、`{spec_value}`、`{quantity}`、`{order_quantity}`、`{amount}`、`{order_amount}`、`{item_detail}`、`{trigger_type}`、`{timestamp}`、`{delivery_unit_index}`、`{delivery_total_count}` 和 `{idempotency_key}`。变量只替换请求头和参数值,不替换 URL 或请求头名称;GET 将参数放入 query,POST 使用 JSON body。响应路径可写成 `data.card.code` 或 `data.cards[0].code`,为空时系统会按 `data`、`content`、`card` 顺序提取。
|
||||
|
||||
请求头和参数会整体加密保存,列表和规则接口只返回是否已配置,不回显密钥明文。编辑时“保留”不会覆盖旧模板,“替换”写入新模板,“清除”删除对应模板。启用幂等重试前必须在请求头或参数中显式写入 `{idempotency_key}`;最多请求 3 次,只重试网络错误、超时、408、429 和 5xx。
|
||||
|
||||
管理员可在系统设置开启“用户配置 HTTP 只能访问公网”。开启后 API 发货、AI、HTTP 通知、远程图片和远程滑块服务不能访问本机、内网、链路本地、保留或云元数据地址,并会在 DNS 解析和重定向时重复校验。该开关默认关闭且保存后立即生效;不要把它当作 API 密钥或请求模板的替代安全措施。
|
||||
|
||||
批量卡密可用“批量导入”创建,也可选择已有 `data` 类型卡密组追加新卡密。上架前检查库存余量;库存不足时应先补货,不要依赖人工补救。
|
||||
|
||||
## 3. 同步或发布商品
|
||||
|
||||
@@ -1,11 +1,2 @@
|
||||
import type { AccountTaskRunResponseEnvelope,AccountTaskSettings,AccountTaskSettingsResponse } from './api';
|
||||
import { get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
|
||||
/** 获取指定账号的自动评价与自动擦亮设置。 */
|
||||
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 });
|
||||
/** 账号任务 Hook 沿用历史模块路径,但全部请求实现只存在于本 feature 的 api adapter。 */
|
||||
export { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api';
|
||||
@@ -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,AccountTaskSettingsResponse } from '../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail,AccountTaskSettingsResponse } from './api';
|
||||
import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi';
|
||||
import { useAccountAutomation } from './accountAutomationHooks';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect,test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail } from './api';
|
||||
import { buildAccountTaskDefaults,canStartAccountTask,isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||
|
||||
// accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。
|
||||
|
||||
@@ -13,14 +13,25 @@ NotificationChannelResponse,
|
||||
NotificationEventType,
|
||||
OperationResponse,
|
||||
QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse
|
||||
} from '../../../shared/api-contract/accounts';
|
||||
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
} from './models';
|
||||
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/accounts';
|
||||
export type * from './models';
|
||||
|
||||
// QRLoginStatusResult 描述账号 feature 消费的非敏感二维码状态字段。
|
||||
export type QRLoginStatusResult = Pick<
|
||||
QRLoginStatusResponse,
|
||||
'status' | 'message' | 'session_id' | 'account_id' | 'is_new_account' | 'verification_screenshot' | 'face_qr_url'
|
||||
>;
|
||||
|
||||
// Accounts
|
||||
// addAccount 新增账号。
|
||||
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
|
||||
return post('/api/v1/accounts', { id, value, login_method: loginMethod });
|
||||
return runContractRequest(/* signal 是本次账号创建请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/accounts', {
|
||||
body: { id, value, login_method: loginMethod },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// accountAvatarURL 生成账号头像地址。
|
||||
@@ -44,7 +55,7 @@ const accountAvatarURL = (item: AccountSummaryResponse, version: string): string
|
||||
// getAccountDetails 读取账号详情。
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => {
|
||||
// data 数据,用于当前 API 处理流程。
|
||||
const response = await get<unknown>('/api/v1/accounts/details', undefined, options);
|
||||
const response = await runContractRequest(/* signal 是本次账号详情读取请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options);
|
||||
// data 是兼容数组、null 和历史 data 包裹后的账号摘要列表。
|
||||
const data = collectionFrom<AccountSummaryResponse>(response, ['data', 'accounts', 'details']);
|
||||
// avatarVersion 头像缓存版本,用于当前 API 处理流程。
|
||||
@@ -77,15 +88,15 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis
|
||||
|
||||
// getAccountTaskSettings 读取账号计划任务设置。
|
||||
export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
|
||||
get(`/api/v1/account-tasks/${id}`, undefined, options);
|
||||
runContractRequest(/* signal 控制账号计划任务读取的取消和超时。 */ signal => contractClient.GET('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, signal }), options);
|
||||
|
||||
// updateAccountTaskSettings 更新账号计划任务设置。
|
||||
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
|
||||
put(`/api/v1/account-tasks/${id}`, settings, options);
|
||||
runContractRequest(/* signal 控制账号计划任务更新的取消和超时。 */ signal => contractClient.PUT('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, body: settings, signal }), 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 });
|
||||
runContractRequest(/* signal 控制账号计划任务立即执行的取消和长超时。 */ signal => contractClient.POST('/api/v1/account-tasks/{cid}/run', { params: { path: { cid: id } }, body: { task_type: taskType }, signal }), { timeoutMs: 120_000, ...options });
|
||||
|
||||
|
||||
export interface AccountRuntimeStatus {
|
||||
@@ -98,21 +109,29 @@ export interface AccountRuntimeStatus {
|
||||
|
||||
// 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 || {};
|
||||
// response 是按账号 ID 索引的非敏感运行状态快照。
|
||||
const response = await runContractRequest(
|
||||
/* signal 是本次账号运行状态读取请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/runtime-status', { signal }),
|
||||
options,
|
||||
);
|
||||
return response;
|
||||
};
|
||||
|
||||
// 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 });
|
||||
return runContractRequest(
|
||||
/* signal 是本次二维码生成请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/qr-login/generate', { signal }),
|
||||
{ ...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 });
|
||||
return runContractRequest(
|
||||
/* requestSignal 是本次二维码轮询请求的超时与取消控制信号。 */ requestSignal => contractClient.GET('/api/v1/qr-login/check/{session_id}', { params: { path: { session_id: sessionId } }, signal: requestSignal }),
|
||||
{ signal, timeoutMs: 10_000 },
|
||||
);
|
||||
};
|
||||
|
||||
// completeQRVerification 完成二维码登录验证。
|
||||
@@ -120,9 +139,11 @@ export const completeQRVerification = async (
|
||||
sessionId: string,
|
||||
targetAccountId?: string,
|
||||
): Promise<QRLoginVerificationResponse> => {
|
||||
return post(`/api/v1/qr-login/complete-verification/${sessionId}`, {
|
||||
target_account_id: targetAccountId || '',
|
||||
});
|
||||
return runContractRequest(/* requestSignal 是本次风控完成请求的超时与取消控制信号。 */ requestSignal => contractClient.POST('/api/v1/qr-login/complete-verification/{session_id}', {
|
||||
params: { path: { session_id: sessionId } },
|
||||
body: { target_account_id: targetAccountId || '' },
|
||||
signal: requestSignal,
|
||||
}));
|
||||
};
|
||||
|
||||
|
||||
@@ -132,32 +153,55 @@ export const completeQRVerification = async (
|
||||
|
||||
// updateAccountStatus 更新账号状态。
|
||||
export const updateAccountStatus = async (id: string, enabled: boolean): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/status`, { enabled });
|
||||
return runContractRequest(/* signal 是本次账号状态更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/status', {
|
||||
params: { path: { cid: id } },
|
||||
body: { enabled },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// deleteAccount 删除账号。
|
||||
export const deleteAccount = async (id: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/accounts/${id}`);
|
||||
return runContractRequest(/* signal 是本次账号删除请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/accounts/{cid}', {
|
||||
params: { path: { cid: id } },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// updateAccountRemark 更新账号备注。
|
||||
export const updateAccountRemark = async (id: string, remark: string): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/remark`, { remark });
|
||||
return runContractRequest(/* signal 是本次账号备注更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/remark', {
|
||||
params: { path: { cid: id } },
|
||||
body: { remark },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// updateAccountAutoConfirm 更新账号自动确认设置。
|
||||
export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm });
|
||||
return runContractRequest(/* signal 是本次账号自动确认更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/auto-confirm', {
|
||||
params: { path: { cid: id } },
|
||||
body: { auto_confirm: autoConfirm },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// 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);
|
||||
return runContractRequest(/* signal 是本次账号暂停时长更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/pause-duration', {
|
||||
params: { path: { cid: id } },
|
||||
body: { pause_duration: pauseDuration },
|
||||
signal,
|
||||
}), 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 });
|
||||
return runContractRequest(/* signal 是本次账号凭据更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}', {
|
||||
params: { path: { cid: id } },
|
||||
body: { id, value, login_method: loginMethod },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
export interface AccountSettingsUpdate {
|
||||
@@ -174,7 +218,11 @@ export interface AccountSettingsUpdate {
|
||||
|
||||
// updateAccountSettings 更新账号设置。
|
||||
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/settings`, data, options);
|
||||
return runContractRequest(/* signal 是本次账号聚合设置更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/settings', {
|
||||
params: { path: { cid: id } },
|
||||
body: data,
|
||||
signal,
|
||||
}), options);
|
||||
};
|
||||
|
||||
export interface LongLoginSettings {
|
||||
@@ -184,12 +232,19 @@ export interface LongLoginSettings {
|
||||
|
||||
// getLongLoginSettings 读取长期登录设置。
|
||||
export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise<LongLoginSettings> => {
|
||||
return get(`/api/v1/accounts/${id}/long-login`, undefined, options);
|
||||
return runContractRequest(/* signal 是本次长期登录设置读取请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/{cid}/long-login', {
|
||||
params: { path: { cid: id } },
|
||||
signal,
|
||||
}), options);
|
||||
};
|
||||
|
||||
// setLongLoginSettings 设置长期登录开关。
|
||||
export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise<LongLoginSettings> => {
|
||||
return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options);
|
||||
return runContractRequest(/* signal 是本次长期登录设置更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/long-login', {
|
||||
params: { path: { cid: id } },
|
||||
body: { enabled },
|
||||
signal,
|
||||
}), options);
|
||||
};
|
||||
|
||||
export interface PasswordLoginStartResponse {
|
||||
@@ -219,22 +274,36 @@ export const passwordLogin = async (data: {
|
||||
/** password 表示密码。 */ password: string;
|
||||
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
|
||||
}, options?: RequestControlOptions): Promise<PasswordLoginStartResponse> => {
|
||||
return post('/api/v1/password-login', data, options);
|
||||
return runContractRequest(/* signal 是永久关闭的密码登录请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/password-login', {
|
||||
body: data,
|
||||
signal,
|
||||
}), 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 });
|
||||
// result 是永久关闭 operation 的理论成功类型;真实服务端恒定返回 password_login_disabled 错误。
|
||||
const result = runContractRequest(/* requestSignal 是永久关闭的密码登录查询请求的超时与取消控制信号。 */ requestSignal => contractClient.GET('/api/v1/password-login/check/{session_id}', {
|
||||
params: { path: { session_id: sessionId } },
|
||||
signal: requestSignal,
|
||||
}), { signal, timeoutMs: 10_000 });
|
||||
return result as unknown as Promise<PasswordLoginStatusResponse>;
|
||||
};
|
||||
|
||||
// cancelPasswordLogin 取消密码登录。
|
||||
export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options);
|
||||
return runContractRequest(/* signal 是永久关闭的密码登录取消请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/password-login/cancel/{session_id}', {
|
||||
params: { path: { session_id: sessionId } },
|
||||
signal,
|
||||
}), options);
|
||||
};
|
||||
|
||||
// refreshAccountProfile 刷新账号资料。
|
||||
export const refreshAccountProfile = async (id: string): Promise<CookieProfileResponse> => {
|
||||
return post(`/api/v1/accounts/${id}/refresh-profile`, {});
|
||||
return runContractRequest(/* signal 是本次账号资料刷新请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/accounts/{cid}/refresh-profile', {
|
||||
params: { path: { cid: id } },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// updateAccountLoginInfo 更新账号登录信息。
|
||||
@@ -244,12 +313,16 @@ export const updateAccountLoginInfo = async (id: string, data: {
|
||||
/** clear_password 表示是否清理登录密码。 */ clear_password?: boolean;
|
||||
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
|
||||
}): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/login-info`, data);
|
||||
return runContractRequest(/* signal 是本次账号登录信息更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/login-info', {
|
||||
params: { path: { cid: id } },
|
||||
body: data,
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// getAllAISettings 读取全部人工智能设置。
|
||||
export const getAllAISettings = async (options?: RequestControlOptions): Promise<Record<string, AIReplySettings>> => {
|
||||
const response = await get<unknown>('/api/v1/settings/ai-reply', undefined, options);
|
||||
const response = await runContractRequest(/* signal 控制全部账号 AI 设置读取的取消和超时。 */ signal => contractClient.GET('/api/v1/settings/ai-reply', { signal }), options) as unknown;
|
||||
// settings 是兼容直接映射、data 包裹和 null 的账号 AI 设置索引。
|
||||
return objectFrom<Record<string, AIReplySettings>>(response, ['settings', 'data', 'result']) || {};
|
||||
};
|
||||
@@ -257,7 +330,7 @@ export const getAllAISettings = async (options?: RequestControlOptions): Promise
|
||||
|
||||
// getAccountAISettings 读取账号人工智能设置。
|
||||
export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise<AIReplySettingsResponse> => {
|
||||
return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options);
|
||||
return runContractRequest(/* signal 控制账号 AI 设置读取的取消和超时。 */ signal => contractClient.GET('/api/v1/settings/ai-reply/{cookie_id}', { params: { path: { cookie_id: cookieId } }, signal }), options) as unknown as Promise<AIReplySettingsResponse>;
|
||||
}
|
||||
|
||||
// updateAccountAISettings 更新账号人工智能设置。
|
||||
@@ -265,12 +338,13 @@ export const updateAccountAISettings = async (cookieId: string, settings: Partia
|
||||
// payload 请求载荷,用于当前 API 处理流程。
|
||||
const payload = {
|
||||
ai_enabled: settings.ai_enabled ?? false,
|
||||
auto_adjust_price_enabled: settings.auto_adjust_price_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);
|
||||
return runContractRequest(/* signal 控制账号 AI 设置更新的取消和超时。 */ signal => contractClient.PUT('/api/v1/settings/ai-reply/{cookie_id}', { params: { path: { cookie_id: cookieId } }, body: payload, signal }), options);
|
||||
}
|
||||
|
||||
|
||||
@@ -291,16 +365,11 @@ const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
|
||||
// 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);
|
||||
const result = await runContractRequest(/* signal 控制账号页通知渠道读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/channels', { signal }), options) as unknown;
|
||||
// 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 = {};
|
||||
}
|
||||
// parsedConfig 是列表摘要刻意不返回渠道秘密时使用的空编辑初始值。
|
||||
const parsedConfig: Record<string, unknown> = {};
|
||||
// normalizedType 是兼容旧渠道别名后的前端渠道类型。
|
||||
const normalizedType = (item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type)) as NotificationChannel['type'];
|
||||
return {
|
||||
@@ -310,8 +379,6 @@ export const getNotificationChannels = async (options?: RequestControlOptions):
|
||||
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 };
|
||||
@@ -321,7 +388,7 @@ export const getNotificationChannels = async (options?: RequestControlOptions):
|
||||
// 账号 ↔ 渠道 绑定(覆盖式)
|
||||
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);
|
||||
const response = await runContractRequest(/* signal 控制账号页通知绑定读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: cookieId } }, signal }), options) as unknown;
|
||||
// result 是去除历史包裹后的账号通知绑定对象。
|
||||
const result = objectFrom<Partial<AccountBindingsResponse>>(response, ['data', 'result']) || {};
|
||||
return Array.isArray(result.channel_ids) ? result.channel_ids : [];
|
||||
|
||||
@@ -24,7 +24,12 @@ export const AccountAISettingsModal: React.FC<AccountAISettingsModalProps> = ({
|
||||
// updateSettings 使用最新草稿合并单个 AI 字段变化。
|
||||
const updateSettings = (patch: Partial<AIReplySettings>) => onChange({ ...settings, ...patch });
|
||||
// handleEnabledChange 切换 AI 自动回复开关。
|
||||
const handleEnabledChange = () => updateSettings({ ai_enabled: !settings.ai_enabled });
|
||||
const handleEnabledChange = () => updateSettings(settings.ai_enabled ? { ai_enabled: false, auto_adjust_price_enabled: false } : { ai_enabled: true });
|
||||
// handleAutoAdjustChange 切换真实订单自动改价开关,AI 议价关闭时不允许单独开启。
|
||||
const handleAutoAdjustChange = () => {
|
||||
if (!settings.ai_enabled) return;
|
||||
updateSettings({ auto_adjust_price_enabled: !settings.auto_adjust_price_enabled });
|
||||
};
|
||||
// handleDiscountPercentChange 更新最大折扣比例。
|
||||
const handleDiscountPercentChange = (event: React.ChangeEvent<HTMLInputElement>) => updateSettings({ max_discount_percent: parseInt(event.target.value, 10) || 0 });
|
||||
// handleDiscountAmountChange 更新最大折扣金额。
|
||||
@@ -53,6 +58,13 @@ export const AccountAISettingsModal: React.FC<AccountAISettingsModalProps> = ({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between p-4 bg-amber-50 border border-amber-200 rounded-xl">
|
||||
<div className="pr-4"><div className="font-bold text-gray-900">自动执行 AI 报价改价</div><div className="text-xs text-gray-600 mt-1">AI 明确报价后,买家在 30 分钟内拍下对应商品时自动修改待付款订单价格。开启 AI 议价后,固定自动化规则改价将不能同时启用。</div></div>
|
||||
<button type="button" onClick={handleAutoAdjustChange} disabled={!settings.ai_enabled} className={`w-14 h-8 rounded-full transition-colors duration-300 relative flex-shrink-0 ${settings.auto_adjust_price_enabled ? 'bg-amber-500' : 'bg-gray-300'} ${!settings.ai_enabled ? 'opacity-50 cursor-not-allowed' : ''}`} aria-label="切换 AI 自动改价">
|
||||
<span className={`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${settings.auto_adjust_price_enabled ? 'translate-x-6' : 'translate-x-0'}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-gray-200 pt-6">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-4">砍价策略</h3>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
@@ -65,7 +77,7 @@ export const AccountAISettingsModal: React.FC<AccountAISettingsModalProps> = ({
|
||||
<div><label className="block text-sm font-bold text-gray-700 mb-2">自定义提示词(可选)</label><textarea value={settings.custom_prompts} onChange={handlePromptChange} placeholder="输入自定义的AI回复规则或风格指引... 例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等" className="w-full ios-input px-4 py-3 rounded-xl h-40 resize-none" /></div>
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
|
||||
<h4 className="font-bold text-blue-900 mb-2 flex items-center gap-2"><Settings className="w-4 h-4" />AI如何工作</h4>
|
||||
<ul className="text-xs text-blue-800 space-y-1"><li>• 自动识别买家的砍价请求</li><li>• 根据设定的策略智能回复</li><li>• 在合理范围内同意降价或礼貌拒绝</li><li>• 保持专业友好的沟通风格</li></ul>
|
||||
<ul className="text-xs text-blue-800 space-y-1"><li>• 自动识别买家的砍价请求</li><li>• 根据设定的策略智能回复</li><li>• 在合理范围内同意降价或礼貌拒绝</li><li>• 只有开启自动改价后,已发送给买家的有效报价才会用于真实订单改价</li></ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup,fireEvent,render,screen } from '@testing-library/react';
|
||||
import { afterEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail,AIReplySettings } from '../../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail,AIReplySettings } from '../api';
|
||||
import { AccountAISettingsModal } from './AccountAISettingsModal';
|
||||
import { AccountCard } from './AccountCard';
|
||||
import { AccountDeleteDialog } from './AccountDeleteDialog';
|
||||
@@ -25,6 +25,7 @@ const accountFixture = {
|
||||
// aiSettingsFixture 是 AI 设置弹窗测试使用的编辑草稿。
|
||||
const aiSettingsFixture: AIReplySettings = {
|
||||
ai_enabled: false,
|
||||
auto_adjust_price_enabled: false,
|
||||
max_discount_percent: 10,
|
||||
max_discount_amount: 100,
|
||||
max_bargain_rounds: 3,
|
||||
@@ -59,13 +60,19 @@ describe('账号 feature 展示组件', /* 当前回调覆盖账号页面子模
|
||||
const onChange = vi.fn();
|
||||
// onSave 是 AI 设置保存测试替身。
|
||||
const onSave = vi.fn();
|
||||
render(<AccountAISettingsModal account={accountFixture} settings={aiSettingsFixture} saving={false} onChange={onChange} onClose={noopAccountAction} onSave={onSave} />);
|
||||
// view 允许测试在 AI 开启后重新渲染同一受控弹窗。
|
||||
const view = render(<AccountAISettingsModal account={accountFixture} settings={aiSettingsFixture} saving={false} onChange={onChange} onClose={noopAccountAction} onSave={onSave} />);
|
||||
fireEvent.click(screen.getByLabelText('切换 AI 自动回复'));
|
||||
fireEvent.change(screen.getByDisplayValue('10'), { target: { value: '20' } });
|
||||
fireEvent.click(screen.getByText('保存'));
|
||||
expect(onChange).toHaveBeenNthCalledWith(1, { ...aiSettingsFixture, ai_enabled: true });
|
||||
expect(onChange).toHaveBeenNthCalledWith(2, { ...aiSettingsFixture, max_discount_percent: 20 });
|
||||
expect(onSave).toHaveBeenCalledTimes(1);
|
||||
// enabledSettings 是 AI 议价已开启、允许商家进一步选择真实自动改价的草稿。
|
||||
const enabledSettings = { ...aiSettingsFixture, ai_enabled: true };
|
||||
view.rerender(<AccountAISettingsModal account={accountFixture} settings={enabledSettings} saving={false} onChange={onChange} onClose={noopAccountAction} onSave={onSave} />);
|
||||
fireEvent.click(screen.getByLabelText('切换 AI 自动改价'));
|
||||
expect(onChange).toHaveBeenNthCalledWith(3, { ...enabledSettings, auto_adjust_price_enabled: true });
|
||||
});
|
||||
|
||||
test('删除确认框展示错误并转发确认动作', /* 当前回调验证删除确认框的错误和提交分支。 */ () => {
|
||||
|
||||
@@ -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 '../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail } from './api';
|
||||
import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api';
|
||||
import { useAccountsData } from './hooks';
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ export const mergeAccountAISettings = (
|
||||
account => ({
|
||||
...account,
|
||||
ai_enabled: allAISettings[account.id]?.ai_enabled ?? false,
|
||||
auto_adjust_price_enabled: allAISettings[account.id]?.auto_adjust_price_enabled ?? false,
|
||||
max_discount_percent: allAISettings[account.id]?.max_discount_percent ?? 10,
|
||||
max_discount_amount: allAISettings[account.id]?.max_discount_amount ?? 100,
|
||||
max_bargain_rounds: allAISettings[account.id]?.max_bargain_rounds ?? 3,
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountDetail {
|
||||
/** 闲鱼账号稳定标识。 */
|
||||
id: string;
|
||||
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
|
||||
cookie_configured?: boolean;
|
||||
/** 账号是否允许运行。 */
|
||||
enabled: boolean;
|
||||
/** 是否自动确认订单。 */
|
||||
auto_confirm: boolean;
|
||||
/** 用户为账号设置的备注。 */
|
||||
remark?: string;
|
||||
/** 自动回复暂停时长,单位为分钟。 */
|
||||
pause_duration?: number;
|
||||
/** 暂停结束时间的 Unix 秒。 */
|
||||
paused_until?: number;
|
||||
/** 当前是否处于暂停状态。 */
|
||||
paused?: boolean;
|
||||
// 登录信息
|
||||
/** 用于密码登录的闲鱼用户名。 */
|
||||
username?: string;
|
||||
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
|
||||
login_password_configured?: boolean;
|
||||
/** 是否在密码登录时显示浏览器。 */
|
||||
show_browser?: boolean;
|
||||
// Frontend helpers
|
||||
/** 平台账号昵称。 */
|
||||
nickname?: string;
|
||||
/** 平台账号头像地址。 */
|
||||
avatar_url?: string;
|
||||
/** 资料刷新失败时的说明。 */
|
||||
profile_error?: string;
|
||||
/** 当前账号运行状态。 */
|
||||
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
|
||||
/** 当前运行状态的用户可见说明。 */
|
||||
runtime_message?: string;
|
||||
/** 当前运行实例是否已连接。 */
|
||||
runtime_connected?: boolean;
|
||||
/** 运行状态快照的更新时间。 */
|
||||
runtime_updated_at?: string;
|
||||
// AI设置
|
||||
/** 是否启用账号 AI 回复。 */
|
||||
ai_enabled?: boolean;
|
||||
/** 是否把 AI 有效报价自动应用到待付款订单。 */
|
||||
auto_adjust_price_enabled?: boolean;
|
||||
/** 允许的最大折扣比例。 */
|
||||
max_discount_percent?: number;
|
||||
/** 允许的最大折扣金额。 */
|
||||
max_discount_amount?: number;
|
||||
/** 允许的最大砍价轮次。 */
|
||||
max_bargain_rounds?: number;
|
||||
/** 账号自定义提示词。 */
|
||||
custom_prompts?: string;
|
||||
// 账号级计划任务
|
||||
/** 是否启用自动评价。 */
|
||||
auto_rate_enabled?: boolean;
|
||||
/** 自动评价使用的文案。 */
|
||||
rate_content?: string;
|
||||
/** 是否启用每日擦亮。 */
|
||||
auto_polish_enabled?: boolean;
|
||||
/** 每日擦亮执行时间。 */
|
||||
polish_time?: string;
|
||||
/** 最近一次自动评价扫描时间。 */
|
||||
last_rate_scan_at?: number;
|
||||
/** 最近一次擦亮日期。 */
|
||||
last_polish_date?: string;
|
||||
/** 最近一次擦亮时间。 */
|
||||
last_polish_at?: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AccountTaskSettings UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountTaskSettings {
|
||||
/** 账号稳定标识。 */
|
||||
account_id: string;
|
||||
/** 是否启用自动评价。 */
|
||||
auto_rate_enabled: boolean;
|
||||
/** 自动评价文案。 */
|
||||
rate_content: string;
|
||||
/** 是否启用每日擦亮。 */
|
||||
auto_polish_enabled: boolean;
|
||||
/** 每日擦亮执行时间。 */
|
||||
polish_time: string;
|
||||
/** 最近一次自动评价扫描时间。 */
|
||||
last_rate_scan_at?: number;
|
||||
/** 最近一次擦亮日期。 */
|
||||
last_polish_date?: string;
|
||||
/** 最近一次擦亮时间。 */
|
||||
last_polish_at?: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AccountTaskSummary UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountTaskSummary {
|
||||
/** 任务类型。 */
|
||||
task_type: 'auto_rate' | 'auto_polish';
|
||||
/** 发现的任务数量。 */
|
||||
found: number;
|
||||
/** 成功处理的任务数量。 */
|
||||
success: number;
|
||||
/** 处理失败的任务数量。 */
|
||||
failed: number;
|
||||
/** 跳过的任务数量。 */
|
||||
skipped: number;
|
||||
/** 批量处理结果说明。 */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AIReplySettings UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AIReplySettings {
|
||||
/** 是否启用账号 AI 回复。 */
|
||||
ai_enabled: boolean;
|
||||
/** 是否自动执行 AI 报价对应的真实订单改价。 */
|
||||
auto_adjust_price_enabled: boolean;
|
||||
/** 最大折扣比例。 */
|
||||
max_discount_percent: number;
|
||||
/** 最大折扣金额。 */
|
||||
max_discount_amount?: number;
|
||||
/** 最大砍价轮次。 */
|
||||
max_bargain_rounds: number;
|
||||
/** 自定义提示词。 */
|
||||
custom_prompts: string;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 NotificationChannelType UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email';
|
||||
/** 由当前 feature adapter 归一后的 NotificationEventType UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type NotificationEventType =
|
||||
| 'account_offline'
|
||||
| 'account_recovered'
|
||||
| 'account_disabled'
|
||||
| 'security_verification'
|
||||
| 'token_renewal'
|
||||
| 'delivery_result'
|
||||
| 'system_error';
|
||||
|
||||
/** 由当前 feature adapter 归一后的 NotificationChannel UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface NotificationChannel {
|
||||
/** 通知渠道标识。 */
|
||||
id: string;
|
||||
/** 通知渠道名称。 */
|
||||
name: string;
|
||||
/** 通知渠道类型。 */
|
||||
type: NotificationChannelType;
|
||||
/** 通知渠道配置。 */
|
||||
config: Record<string, unknown>;
|
||||
/** 渠道绑定的事件类型。 */
|
||||
event_types?: NotificationEventType[];
|
||||
/** 通知渠道是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 创建时间。 */
|
||||
created_at?: string;
|
||||
/** 更新时间。 */
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
/** 账号编辑器读取的通知渠道传输结果,仅用于适配为 NotificationChannel UI 模型。 */
|
||||
export interface NotificationChannelResponse {
|
||||
/** 通知渠道数值标识。 */ id: number;
|
||||
/** 用户可见渠道名称。 */ name: string;
|
||||
/** 服务端保存的渠道类型。 */ type: string;
|
||||
/** 兼容 JSON 文本的事件订阅列表。 */ event_types?: string;
|
||||
/** 渠道是否参与投递。 */ enabled: boolean;
|
||||
}
|
||||
|
||||
/** 账号列表接口返回的非敏感具名 DTO。 */
|
||||
/** 由当前 feature adapter 归一后的 AccountSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountSummaryResponse {
|
||||
/** 闲鱼账号稳定标识。 */
|
||||
id: string;
|
||||
/** 数据库中是否存在账号记录。 */
|
||||
has_cookie: boolean;
|
||||
/** 账号是否允许运行。 */
|
||||
enabled: boolean;
|
||||
/** 是否自动确认订单。 */
|
||||
auto_confirm: boolean;
|
||||
/** 账号备注。 */
|
||||
remark: string;
|
||||
/** 自动回复暂停时长,单位为分钟。 */
|
||||
pause_duration: number;
|
||||
/** 暂停结束 Unix 秒。 */
|
||||
paused_until: number;
|
||||
/** 当前是否仍处于暂停状态。 */
|
||||
paused: boolean;
|
||||
/** 密码登录用户名。 */
|
||||
username: string;
|
||||
/** 是否允许密码登录显示浏览器;兼容旧服务端的 0/1 字符串值。 */
|
||||
show_browser: boolean | number | string;
|
||||
/** 平台昵称缓存。 */
|
||||
nickname: string;
|
||||
/** 平台头像地址。 */
|
||||
avatar_url: string;
|
||||
/** 最近一次成功登录方式。 */
|
||||
login_method: string;
|
||||
/** 最近一次成功登录时间。 */
|
||||
last_login_at: number;
|
||||
/** 资料刷新错误说明。 */
|
||||
profile_error: string;
|
||||
/** 账号级 AI 回复开关。 */
|
||||
ai_enabled: boolean;
|
||||
/** 自动评价计划开关。 */
|
||||
auto_rate_enabled: boolean;
|
||||
/** 自动评价文案。 */
|
||||
rate_content: string;
|
||||
/** 自动擦亮计划开关。 */
|
||||
auto_polish_enabled: boolean;
|
||||
/** 自动擦亮本地时间。 */
|
||||
polish_time: string;
|
||||
/** 最近一次自动评价扫描时间。 */
|
||||
last_rate_scan_at: number;
|
||||
/** 最近一次自动擦亮日期。 */
|
||||
last_polish_date: string;
|
||||
/** 最近一次自动擦亮时间。 */
|
||||
last_polish_at: number;
|
||||
}
|
||||
|
||||
/** 账号设置变更接口的具名成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 CookieSettingsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface CookieSettingsResponse {
|
||||
/** 表示设置是否保存成功。 */
|
||||
success: boolean;
|
||||
/** 暂停结束 Unix 秒。 */
|
||||
paused_until: number;
|
||||
/** 表示账号当前是否暂停。 */
|
||||
paused: boolean;
|
||||
}
|
||||
|
||||
/** 账号资料刷新接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 CookieProfileResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface CookieProfileResponse {
|
||||
/** 表示资料刷新是否成功。 */
|
||||
success: boolean;
|
||||
/** 账号稳定标识。 */
|
||||
id: string;
|
||||
/** 平台账号昵称。 */
|
||||
nickname: string;
|
||||
/** 平台账号头像地址。 */
|
||||
avatar_url: string;
|
||||
/** 资料刷新错误说明。 */
|
||||
profile_error: string;
|
||||
}
|
||||
|
||||
/** 账号暂停时长查询接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 PauseDurationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface PauseDurationResponse {
|
||||
/** 暂停时长,单位为分钟。 */
|
||||
pause_duration: number;
|
||||
/** 暂停结束 Unix 秒。 */
|
||||
paused_until: number;
|
||||
/** 表示账号当前是否暂停。 */
|
||||
paused: boolean;
|
||||
}
|
||||
|
||||
/** 账号 AI 回复设置接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AIReplySettingsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AIReplySettingsResponse {
|
||||
/** 账号稳定标识;默认配置响应可能省略。 */
|
||||
cookie_id?: string;
|
||||
/** AI 回复是否启用。 */
|
||||
ai_enabled: boolean;
|
||||
/** 有效 AI 报价是否会自动触发真实订单改价。 */
|
||||
auto_adjust_price_enabled: boolean;
|
||||
/** 最大折扣比例。 */
|
||||
max_discount_percent: number;
|
||||
/** 最大折扣金额。 */
|
||||
max_discount_amount: number;
|
||||
/** 最大砍价轮次。 */
|
||||
max_bargain_rounds: number;
|
||||
/** 自定义提示词。 */
|
||||
custom_prompts: string;
|
||||
}
|
||||
|
||||
/** 通知绑定列表中的单条记录。 */
|
||||
/** 由当前 feature adapter 归一后的 NotificationBinding UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface NotificationBinding {
|
||||
/** 账号稳定标识,列表归一化后补充。 */
|
||||
cookie_id?: string;
|
||||
/** 绑定记录主键。 */
|
||||
id?: number;
|
||||
/** 通知渠道主键。 */
|
||||
channel_id: number;
|
||||
/** 通知渠道名称。 */
|
||||
channel_name: string;
|
||||
/** 绑定是否启用。 */
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** 账号通知渠道绑定查询响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AccountBindingsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountBindingsResponse {
|
||||
/** 账号稳定标识。 */
|
||||
cookie_id: string;
|
||||
/** 已绑定通知渠道主键列表。 */
|
||||
channel_ids: number[];
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
|
||||
/** 账号任务设置响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AccountTaskSettingsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountTaskSettingsResponse {
|
||||
/** 账号稳定标识。 */
|
||||
account_id: string;
|
||||
/** 是否启用自动评价。 */
|
||||
auto_rate_enabled: boolean;
|
||||
/** 自动评价文案。 */
|
||||
rate_content: string;
|
||||
/** 是否启用自动擦亮。 */
|
||||
auto_polish_enabled: boolean;
|
||||
/** 自动擦亮本地时间。 */
|
||||
polish_time: string;
|
||||
/** 最近一次评价扫描时间。 */
|
||||
last_rate_scan_at: number;
|
||||
/** 最近一次擦亮日期。 */
|
||||
last_polish_date: string;
|
||||
/** 最近一次擦亮时间。 */
|
||||
last_polish_at: number;
|
||||
}
|
||||
|
||||
/** 账号任务执行记录响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AccountTaskRunResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountTaskRunResponse {
|
||||
/** 任务执行记录主键。 */
|
||||
id: number;
|
||||
/** 任务幂等键。 */
|
||||
run_key: string;
|
||||
/** 账号稳定标识。 */
|
||||
account_id: string;
|
||||
/** 任务类型。 */
|
||||
task_type: string;
|
||||
/** 任务目标标识。 */
|
||||
target_id: string;
|
||||
/** 任务业务日期。 */
|
||||
run_date: string;
|
||||
/** 任务执行状态。 */
|
||||
status: string;
|
||||
/** 任务成功数量。 */
|
||||
success_count: number;
|
||||
/** 任务失败数量。 */
|
||||
failed_count: number;
|
||||
/** 任务失败说明。 */
|
||||
error_message: string;
|
||||
/** 下一次重试时间。 */
|
||||
next_retry_at: number;
|
||||
/** 任务开始时间。 */
|
||||
started_at: number;
|
||||
/** 任务完成时间。 */
|
||||
finished_at: number;
|
||||
}
|
||||
|
||||
/** 账号任务执行记录列表响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AccountTaskRunsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountTaskRunsResponse {
|
||||
/** 当前账号的任务执行记录。 */
|
||||
runs: AccountTaskRunResponse[];
|
||||
}
|
||||
|
||||
/** 手动执行账号任务的统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AccountTaskSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountTaskSummaryResponse extends AccountTaskSummary {
|
||||
/** 任务结果说明。 */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** 手动执行账号任务的成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AccountTaskRunResponseEnvelope UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountTaskRunResponseEnvelope {
|
||||
/** 任务请求是否成功完成。 */
|
||||
success: boolean;
|
||||
/** 账号任务执行统计。 */
|
||||
summary: AccountTaskSummaryResponse;
|
||||
}
|
||||
|
||||
/** 扫码登录二维码生成响应。 */
|
||||
/** 由当前 feature adapter 归一后的 QRLoginGenerateResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface QRLoginGenerateResponse {
|
||||
/** 二维码是否生成成功。 */
|
||||
success: boolean;
|
||||
/** 扫码登录会话标识。 */
|
||||
session_id: string;
|
||||
/** 二维码图片地址。 */
|
||||
qr_code_url: string;
|
||||
/** 可选的提示文本。 */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** 二维码登录状态响应。 */
|
||||
/** 由当前 feature adapter 归一后的 QRLoginStatusResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface QRLoginStatusResponse {
|
||||
/** 当前二维码会话状态。 */
|
||||
status: string;
|
||||
/** 风控验证页面截图地址,在人脸二维码不可用时作为展示兜底。 */
|
||||
verification_screenshot?: string;
|
||||
/** 闲鱼人脸风控验证二维码地址,验证页面优先展示。 */
|
||||
face_qr_url?: string;
|
||||
/** 扫码登录会话标识。 */
|
||||
session_id?: string;
|
||||
/** 持久化后的本地账号标识。 */
|
||||
account_id?: string;
|
||||
/** 是否新建了本地账号。 */
|
||||
is_new_account?: boolean;
|
||||
/** 状态提示文本。 */
|
||||
message?: string;
|
||||
/** 兼容上游可能扩展的非敏感状态字段。 */
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** 二维码验证完成响应。 */
|
||||
/** 由当前 feature adapter 归一后的 QRLoginVerificationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface QRLoginVerificationResponse {
|
||||
/** 验证结果是否成功。 */
|
||||
success: boolean;
|
||||
/** 平台账号标识。 */
|
||||
unb?: string;
|
||||
/** 持久化后的本地账号标识。 */
|
||||
account_id?: string;
|
||||
/** 是否新建了本地账号。 */
|
||||
is_new_account?: boolean;
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail } from '../api';
|
||||
|
||||
// accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。
|
||||
const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({
|
||||
|
||||
@@ -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 '../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail } from './api';
|
||||
|
||||
// qrLoginMocks 保存二维码登录协调器测试使用的接口替身。
|
||||
const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({
|
||||
@@ -59,7 +59,7 @@ describe('useAccountQRCodeLogin 二维码登录协调器', /* 当前回调验证
|
||||
expect(hook.result.current.qrStatus).toBe('waiting');
|
||||
expect(hook.result.current.qrCodeUrl).toBe('qr-url');
|
||||
|
||||
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'user-1' });
|
||||
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'success' });
|
||||
await act(/* pollAction 触发二维码状态轮询。 */ async () => {
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await flushMicrotasks();
|
||||
|
||||
@@ -111,7 +111,7 @@ export const useAccountQRCodeLogin = ({ onLoginSuccess }: AccountQRCodeLoginOpti
|
||||
// response 保存风控验证完成接口返回值。
|
||||
const response = await completeQRVerification(sessionId, target?.id);
|
||||
if (!response.success || !response.account_id) {
|
||||
throw new Error(response.message || '保存扫码授权失败');
|
||||
throw new Error('保存扫码授权失败');
|
||||
}
|
||||
return response.account_id;
|
||||
};
|
||||
|
||||
@@ -36,7 +36,7 @@ test('QR poller stops on success and terminal errors', /* 当前回调处理用
|
||||
vi.useFakeTimers();
|
||||
// checkStatus check状态,负责当前功能中的对应处理。
|
||||
const checkStatus = vi.fn()
|
||||
.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'acc1' })
|
||||
.mockResolvedValueOnce({ status: 'success' })
|
||||
.mockResolvedValueOnce({ status: 'expired' });
|
||||
// onSuccess 响应当前用户操作(Success)。
|
||||
const onSuccess = vi.fn();
|
||||
@@ -53,7 +53,7 @@ test('QR poller stops on success and terminal errors', /* 当前回调处理用
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(onSuccess).toHaveBeenCalledWith({ status: 'success', cookies: 'a=b', unb: 'acc1' });
|
||||
expect(onSuccess).toHaveBeenCalledWith({ status: 'success' });
|
||||
expect(poller.isActive()).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(4000);
|
||||
expect(checkStatus).toHaveBeenCalledTimes(1);
|
||||
@@ -76,7 +76,6 @@ test('QR poller keeps polling during verification and stops on thrown errors', /
|
||||
const checkStatus = vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
status: 'verification_required',
|
||||
verification_url: 'https://verify.example',
|
||||
face_qr_url: 'https://face.example',
|
||||
})
|
||||
.mockRejectedValueOnce(new Error('network down'));
|
||||
|
||||
@@ -1,18 +1,4 @@
|
||||
// QRLoginStatusResult 描述二维码登录状态接口返回的可选字段。
|
||||
export interface QRLoginStatusResult {
|
||||
// status 表示当前二维码登录状态。
|
||||
status?: string;
|
||||
// cookies 表示登录成功后返回的凭证字符串。
|
||||
cookies?: string;
|
||||
// unb 表示闲鱼账号的用户标识。
|
||||
unb?: string;
|
||||
// verification_url 表示风控验证地址。
|
||||
verification_url?: string;
|
||||
// verification_screenshot 表示风控验证截图地址。
|
||||
verification_screenshot?: string;
|
||||
// face_qr_url 表示人脸验证二维码地址。
|
||||
face_qr_url?: string;
|
||||
}
|
||||
import type { QRLoginStatusResult } from './api';
|
||||
|
||||
// QRLoginPollerTimers 描述轮询器使用的定时器依赖,便于测试替换时间源。
|
||||
interface QRLoginPollerTimers {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail } from './api';
|
||||
import { accountRuntimePresentation,isOlderStatus,mergeAccountRuntimeStatuses } from './runtime';
|
||||
|
||||
// account 创建运行状态测试使用的最小账号对象。
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect,test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail } from './api';
|
||||
import {
|
||||
buildAccountLoginInfoUpdate,
|
||||
isCurrentAccountRequest,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import type { Dispatch,SetStateAction } from 'react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail,AIReplySettings } from '../../../shared/api-contract/accounts';
|
||||
import type { AccountDetail,AIReplySettings } from './api';
|
||||
import {
|
||||
cancelPasswordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
@@ -61,7 +61,7 @@ const accountFixture = { id: 'account-1', enabled: true, value: 'old-cookie', re
|
||||
// editFormFixture 是账号编辑弹窗的初始表单。
|
||||
const editFormFixture: AccountEditForm = { remark: '新备注', cookie: 'new-cookie', auto_confirm: true, pause_duration: 60, username: 'user@example.com', login_password: 'new-password', show_browser: true, showLoginPassword: false, clear_password: false };
|
||||
// aiFixture 是账号 AI 设置的服务端配置。
|
||||
const aiFixture: AIReplySettings = { ai_enabled: true, max_discount_percent: 20, max_discount_amount: 50, max_bargain_rounds: 2, custom_prompts: '请礼貌回复' };
|
||||
const aiFixture: AIReplySettings = { ai_enabled: true, auto_adjust_price_enabled: true, max_discount_percent: 20, max_discount_amount: 50, max_bargain_rounds: 2, custom_prompts: '请礼貌回复' };
|
||||
|
||||
describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知绑定和密码登录。 */ () => {
|
||||
beforeEach(/* 当前回调重置账号子模块 API 替身。 */ () => {
|
||||
|
||||
@@ -41,7 +41,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
// bindingsLoadError 保存通知绑定加载错误。
|
||||
const [bindingsLoadError, setBindingsLoadError] = useState('');
|
||||
// aiSettings 保存账号 AI 编辑草稿。
|
||||
const [aiSettings, setAiSettings] = useState<AIReplySettings>({ ai_enabled: false, max_discount_percent: 10, max_discount_amount: 100, max_bargain_rounds: 3, custom_prompts: '' });
|
||||
const [aiSettings, setAiSettings] = useState<AIReplySettings>({ ai_enabled: false, auto_adjust_price_enabled: false, max_discount_percent: 10, max_discount_amount: 100, max_bargain_rounds: 3, custom_prompts: '' });
|
||||
// saving 表示编辑、AI 或暂停动作是否正在保存。
|
||||
const [saving, setSaving] = useState(false);
|
||||
// passwordLoginView 保存密码登录刷新授权状态。
|
||||
@@ -168,7 +168,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
// settings 保存当前账号的 AI 设置。
|
||||
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
|
||||
if (!isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) return;
|
||||
setAiSettings({ 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 ?? '' });
|
||||
setAiSettings({ ai_enabled: settings.ai_enabled ?? false, auto_adjust_price_enabled: settings.auto_adjust_price_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 ?? '' });
|
||||
} catch (/* error 保存 AI 设置读取请求的失败原因,过期请求不会更新当前界面。 */ error) {
|
||||
// error 保存 AI 设置读取失败原因。
|
||||
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) console.error('加载 AI 设置失败:', error);
|
||||
|
||||
@@ -29,21 +29,47 @@ import { appendCardData,batchCreateCards,createCard,deleteCard,getCardDetails,ge
|
||||
import { getChatMessagePage,getChatMessages,getChatSessionPage,getChatSessions,markChatRead,sendChatImage,sendChatMessage } from './chat/api';
|
||||
import { getDashboardStats,getOrderAnalytics,getValidOrders } from './dashboard/api';
|
||||
import { cancelItemPublishBatch,createItem,deleteItem,deleteItemPublishBatch,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 { createNotificationChannel,deleteAccountNotifications,deleteMessageNotification,deleteNotificationChannel,getAccountBindings,getMessageNotifications,getNotificationChannels,setAccountBindings,setMessageNotification,testNotificationChannel,updateNotificationChannel,updateSystemSettings as updateNotificationSystemSettings } 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';
|
||||
import { normalizeSystemSettingsUpdate } from '../../shared/api-contract/settings';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
} /* 测试回调验证:全局 API 适配器测试环境清理。 */);
|
||||
|
||||
// stubContractFetch 将 openapi-fetch 交给共享客户端的 Request 归一成历史断言使用的路径和请求体;生产运行时不会读取或重建该请求。
|
||||
const stubContractFetch = (fetchMock: typeof fetch): void => {
|
||||
vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
// request 保存 openapi-fetch 已序列化的请求;测试替身读取 clone,不会消费生产请求体。
|
||||
const request = input instanceof Request ? input : new Request(input, init);
|
||||
// requestURL 用于把 Node 测试环境中的绝对占位 URL 还原为断言使用的 API 相对路径。
|
||||
const requestURL = new URL(request.url);
|
||||
// contentType 决定请求体在测试替身中的可读方式,multipart 保持 FormData 便于断言重复文件字段。
|
||||
const contentType = request.headers.get('content-type') || '';
|
||||
// body 是仅供适配器断言检查的克隆请求体;GET/HEAD 没有请求体。
|
||||
const body: BodyInit | undefined = request.method === 'GET' || request.method === 'HEAD'
|
||||
? undefined
|
||||
: contentType.includes('multipart/form-data')
|
||||
? await request.clone().formData()
|
||||
: await request.clone().text();
|
||||
return fetchMock(`${requestURL.pathname}${requestURL.search}`, {
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
body,
|
||||
signal: request.signal,
|
||||
credentials: 'include',
|
||||
});
|
||||
} /* 测试 fetch 回调将 Request clone 归一给历史 fetchMock 断言,生产请求不会走该回调。 */);
|
||||
};
|
||||
|
||||
test('updateSystemSettings uses one atomic bulk request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await updateSystemSettings({ theme_color: 'blue', renewal_log_retention_days: 15 });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/settings/system', expect.objectContaining({ method: 'PUT', credentials: 'include' }));
|
||||
@@ -53,7 +79,7 @@ test('updateSystemSettings uses one atomic bulk request', async () => {
|
||||
test('updateSystemSettings separates sensitive values into explicit commands', /* 当前回调验证敏感设置三态命令请求体。 */ async () => {
|
||||
// fetchMock 是系统设置更新请求的 HTTP 替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await updateSystemSettings({ ai_api_key: 'new-secret', smtp_password: '' });
|
||||
// payload 是普通设置与敏感命令分离后的请求体。
|
||||
const payload = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
@@ -64,10 +90,48 @@ test('updateSystemSettings separates sensitive values into explicit commands', /
|
||||
});
|
||||
});
|
||||
|
||||
test('normalizeSystemSettingsUpdate separates every sensitive system setting', /* 当前回调验证共享归一器不会遗漏任一敏感系统设置。 */ () => {
|
||||
// payload 是混合普通值和四类敏感值后的系统设置命令。
|
||||
const payload = normalizeSystemSettingsUpdate({
|
||||
theme_color: 'blue',
|
||||
ai_api_key: 'test-ai-key',
|
||||
smtp_password: 'test-smtp-password',
|
||||
qq_reply_secret_key: 'test-qq-secret',
|
||||
'captcha.remote_secret_key': 'test-captcha-secret',
|
||||
});
|
||||
expect(payload.values).toEqual({ theme_color: 'blue' });
|
||||
expect(payload.secrets).toEqual({
|
||||
ai_api_key: { action: 'replace', value: 'test-ai-key' },
|
||||
smtp_password: { action: 'replace', value: 'test-smtp-password' },
|
||||
qq_reply_secret_key: { action: 'replace', value: 'test-qq-secret' },
|
||||
'captcha.remote_secret_key': { action: 'replace', value: 'test-captcha-secret' },
|
||||
});
|
||||
});
|
||||
|
||||
test('notification SMTP settings separate the authorization code into a secret command', /* 当前回调验证通知页不会把 SMTP 授权码写入普通设置。 */ async () => {
|
||||
// fetchMock 是通知页系统设置更新请求的 HTTP 替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
stubContractFetch(fetchMock);
|
||||
await updateNotificationSystemSettings({
|
||||
smtp_server: 'smtp.example.com', smtp_port: 465, smtp_user: 'sender@example.com',
|
||||
smtp_password: 'test-smtp-secret', qq_reply_secret_key: 'test-qq-secret',
|
||||
'captcha.remote_secret_key': 'test-captcha-secret',
|
||||
});
|
||||
// payload 是通知页适配器分流后的普通设置和敏感命令。
|
||||
const payload = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(payload.values).toEqual({ smtp_server: 'smtp.example.com', smtp_port: 465, smtp_user: 'sender@example.com' });
|
||||
expect(payload.secrets).toEqual({
|
||||
smtp_password: { action: 'replace', value: 'test-smtp-secret' },
|
||||
qq_reply_secret_key: { action: 'replace', value: 'test-qq-secret' },
|
||||
'captcha.remote_secret_key': { action: 'replace', value: 'test-captcha-secret' },
|
||||
});
|
||||
expect(payload.values).not.toHaveProperty('smtp_password');
|
||||
});
|
||||
|
||||
test('health API exposes build metadata through the request boundary', async () => {
|
||||
// fetchMock 是健康检查 API 的请求替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ version: '1.2.3', commit: 'abc123' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
const controller = new AbortController(); /* controller 表示controller。 */
|
||||
|
||||
await expect(getHealth({ signal: controller.signal })).resolves.toEqual({ version: '1.2.3', commit: 'abc123' });
|
||||
@@ -79,7 +143,7 @@ test('chat APIs preserve account and conversation scope', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ sessions: [{ account_id: 'a1', chat_id: 'c1' }] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ messages: [{ account_id: 'a1', chat_id: 'c1', id: 1 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true, message: { id: 2 } })) /* 模拟新增动作接口返回包含标识的成功响应。 */); /* fetchMock 是本测试替代浏览器网络层的请求桩。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await getChatSessions('a1');
|
||||
await getChatMessages('a1', 'c1', 9);
|
||||
await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' });
|
||||
@@ -98,7 +162,7 @@ test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, message: { message_key: 'm1' } }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, message: { message_key: 'm2' } }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// controller 是 Chat feature Hook 使用的请求控制器。
|
||||
const controller = new AbortController();
|
||||
await getChatSessionPage('a1', undefined, { signal: controller.signal });
|
||||
@@ -115,7 +179,7 @@ test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
|
||||
|
||||
test('account task APIs keep rating and polish account-scoped', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })) /* 模拟账号任务执行后返回任务摘要。 */); /* fetchMock 是本测试替代浏览器网络层的请求桩。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await updateAccountTaskSettings('a1', {
|
||||
account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快',
|
||||
auto_polish_enabled: true, polish_time: '03:00',
|
||||
@@ -133,7 +197,7 @@ test('账号自动任务 API 转发外部取消信号', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, summary: { task_type: 'auto_rate', found: 1, success: 1, failed: 0, skipped: 0 } }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// controller 是 AccountAutomation feature Hook 使用的请求控制器。
|
||||
const controller = new AbortController();
|
||||
const settings = { account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' }; /* settings 表示settings。 */
|
||||
@@ -147,7 +211,7 @@ test('账号自动任务 API 转发外部取消信号', async () => {
|
||||
|
||||
test('getItemPublishBatches unwraps persisted batch list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ batches: [{ id: 'batch-1', status: 'running' }] })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await expect(getItemPublishBatches(10)).resolves.toEqual([{ id: 'batch-1', status: 'running' }]);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/items/publish-batches?limit=10', expect.objectContaining({ credentials: 'include' }));
|
||||
} /* 测试回调验证:getItemPublishBatches unwraps persisted batch list。 */);
|
||||
@@ -156,7 +220,7 @@ test('automation issue APIs expose and resolve quarantined work', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ runs: [{ id: 1 }], pending_tasks: [{ id: 2 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true })) /* 模拟无消息体的成功操作响应。 */); /* fetchMock 是本测试替代浏览器网络层的请求桩。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await expect(getAutomationIssues()).resolves.toEqual({ runs: [{ id: 1 }], pending_tasks: [{ id: 2 }] });
|
||||
await resolveAutomationRun(1, 'continue');
|
||||
await resolveDeferredAutomationTask(2, 'retry');
|
||||
@@ -165,24 +229,24 @@ test('automation issue APIs expose and resolve quarantined work', async () => {
|
||||
expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/automation-pending-tasks/2/resolve');
|
||||
} /* 测试回调验证:automation issue APIs expose and resolve quarantined work。 */);
|
||||
|
||||
test('order multipart requests use the shared authenticated form request path', async () => {
|
||||
test('order refresh uses JSON while file import keeps the shared authenticated multipart path', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-1', status: 'running' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-1', status: 'succeeded', result: { partial_failure: false, message: '同步完成', summary: { discovered: 0, list_updated: 0, soft_deleted: 0, detail_total: 0, total: 0, updated: 0, no_change: 0, failed: 0 }, results: [] } }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await syncOrders('acc1', 'pending_ship');
|
||||
await importOrders(new FormData());
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/orders/refresh', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/orders/refresh', expect.objectContaining({ method: 'POST', credentials: 'include', body: JSON.stringify({ cookie_id: 'acc1', status: 'pending_ship' }) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/refresh/job-1', expect.objectContaining({ method: 'GET', credentials: 'include' }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/orders/import', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
|
||||
} /* 测试回调验证:order multipart requests use the shared authenticated form request path。 */);
|
||||
} /* 测试回调验证:新版订单刷新使用 JSON,而订单文件导入保持共享 multipart 路径。 */);
|
||||
|
||||
test('syncOrders surfaces failed persisted job status', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-failed', status: 'running' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-failed', status: 'failed', error_message: '平台会话已过期' })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await expect(syncOrders()).rejects.toThrow('平台会话已过期');
|
||||
} /* 测试回调验证:syncOrders surfaces failed persisted job status。 */);
|
||||
|
||||
@@ -191,7 +255,7 @@ test('syncOrders aborts while waiting for persisted job status', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-running', status: 'running' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-running', status: 'running' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-running', status: 'cancelled' })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// controller 控制订单刷新轮询的取消信号。
|
||||
const controller = new AbortController();
|
||||
// pending 保存等待取消结果的订单刷新请求。
|
||||
@@ -209,7 +273,7 @@ test('syncOrders reaches the front-end budget, cancels, and returns a concurrent
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-timeout', status: 'running' }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ error: { code: 'conflict', message: '任务已结束' } }), { status: 409, headers: { 'content-type': 'application/json' } }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-timeout', status: 'succeeded', result: { partial_failure: false, message: '终态成功', summary: { discovered: 0, list_updated: 0, soft_deleted: 0, detail_total: 0, total: 0, updated: 0, no_change: 0, failed: 0 }, results: [] } }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
// result 保存达到本地等待预算后由终态复查返回的成功订单刷新结果。
|
||||
const result = await syncOrders(undefined, undefined, { pollLimit: 1, pollIntervalMs: 0 });
|
||||
@@ -225,7 +289,7 @@ test('syncOrders reports a timeout only after cancellation and final terminal re
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-still-running', status: 'running' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-still-running', status: 'cancelled' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-still-running', status: 'cancelled' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await expect(syncOrders(undefined, undefined, { pollLimit: 1, pollIntervalMs: 0 })).rejects.toThrow('订单刷新任务等待超时,已请求取消');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/orders/refresh/job-still-running', expect.objectContaining({ method: 'DELETE', credentials: 'include' }));
|
||||
@@ -233,13 +297,13 @@ test('syncOrders reports a timeout only after cancellation and final terminal re
|
||||
|
||||
test('cancelOrderRefreshJob sends a user-scoped delete command', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, job_id: 'job-cancel', status: 'cancelled' })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await expect(cancelOrderRefreshJob('job-cancel')).resolves.toEqual({ success: true, job_id: 'job-cancel', status: 'cancelled' });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/orders/refresh/job-cancel', expect.objectContaining({ method: 'DELETE', credentials: 'include' }));
|
||||
} /* 测试回调验证:cancelOrderRefreshJob sends a user-scoped delete command。 */);
|
||||
|
||||
test('legacy notification channel aliases are normalized for the editor', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{ id: 1, name: '旧飞书', type: 'lark', config: 'not-json', enabled: true }])));
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse([{ id: 1, name: '旧飞书', type: 'lark', config: 'not-json', enabled: true }])));
|
||||
const result = await getNotificationChannels(); /* result 表示处理结果。 */
|
||||
expect(result.data?.[0]).toMatchObject({ type: 'feishu', config: {} });
|
||||
} /* 测试回调验证:legacy notification channel aliases are normalized for the editor。 */);
|
||||
@@ -254,7 +318,7 @@ test('getOrders normalizes backend order fields', async () => {
|
||||
orders: [{ order_id: 'o1', order_status: 'shipped', quantity: '2' }],
|
||||
total: 1,
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
const result = await getOrders(undefined, 'all', 1, 20, ' buyer '); /* result 表示处理结果。 */
|
||||
expect(result.data[0]).toMatchObject({ id: 'o1', status: 'shipped', quantity: 2 });
|
||||
expect(result.total).toBe(1);
|
||||
@@ -262,7 +326,7 @@ test('getOrders normalizes backend order fields', async () => {
|
||||
} /* 测试回调验证:getOrders normalizes backend order fields。 */);
|
||||
|
||||
test('getOrders maps unsupported backend statuses to unknown', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse({
|
||||
data: [{ order_id: 'o-unknown', order_status: 'legacy_status' }],
|
||||
})));
|
||||
const result = await getOrders(); /* result 表示处理结果。 */
|
||||
@@ -274,7 +338,7 @@ test('订单查询和导入 API 转发外部取消信号', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ data: [], total_pages: 1 }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success_count: 1, failed_count: 0, results: [] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// controller 是 feature Hook 传入 API 的取消控制器。
|
||||
const controller = new AbortController();
|
||||
await getOrders(undefined, 'all', 1, 20, '', { signal: controller.signal });
|
||||
@@ -291,7 +355,7 @@ test('Dashboard 统计 API 转发外部取消信号', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ revenue_stats: { total_amount: 1, total_orders: 1 }, daily_stats: [] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ revenue_stats: { total_amount: 0, total_orders: 0 }, daily_stats: [] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ orders: [], total: 0, truncated: false }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// controller 是 Dashboard feature Hook 传入 API 的请求控制器。
|
||||
const controller = new AbortController();
|
||||
await getDashboardStats({ signal: controller.signal });
|
||||
@@ -310,7 +374,7 @@ test('Settings 配置、模型和凭据 API 转发外部取消信号', async ()
|
||||
.mockResolvedValueOnce(jsonResponse({ models: ['model-a'] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ authenticated: true, username: 'admin' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, message: '已更新' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// controller 是 Settings feature Hook 使用的请求控制器。
|
||||
const controller = new AbortController();
|
||||
await getSystemSettings({ signal: controller.signal });
|
||||
@@ -330,7 +394,7 @@ test('通知渠道和 SMTP API 转发外部取消信号', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ data: {} }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// controller 是通知 feature 传给服务 API 的共享取消控制器。
|
||||
const controller = new AbortController();
|
||||
await getNotificationChannels({ signal: controller.signal });
|
||||
@@ -352,7 +416,7 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
|
||||
total_pages: 2,
|
||||
trigger_counts: { order_paid: 8, buyer_reviewed: 7, review_missing_timeout: 6 },
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
const result = await getShippingRulesPage({
|
||||
cookieId: 'acc1',
|
||||
@@ -381,7 +445,7 @@ test('getValidOrders accepts wrapped responses', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o2', order_status: 'completed', quantity: '3' }],
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-480);
|
||||
const result = await getValidOrders({ start_date: '2026-01-01', end_date: '2026-01-02' }); /* result 表示处理结果。 */
|
||||
expect(result).toEqual({
|
||||
@@ -394,7 +458,7 @@ test('getValidOrders accepts wrapped responses', async () => {
|
||||
|
||||
test('getOrderAnalytics sends the browser timezone offset', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ revenue_stats: {}, daily_stats: [], status_stats: [], city_stats: [] })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-330);
|
||||
await getOrderAnalytics({ start_date: '2026-01-01', end_date: '2026-01-02' });
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('timezone_offset_minutes=330');
|
||||
@@ -403,7 +467,7 @@ test('getOrderAnalytics sends the browser timezone offset', async () => {
|
||||
test('getOrderAnalytics 支持数字天数参数', /* 当前回调验证订单分析默认日期范围构造。 */ async () => {
|
||||
// fetchMock 是数字天数分析请求的网络替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ revenue_stats: {}, daily_stats: [], status_stats: [], city_stats: [] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await getOrderAnalytics(3);
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('/api/v1/analytics/orders?');
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('start_date=');
|
||||
@@ -413,21 +477,21 @@ test('getOrderAnalytics 支持数字天数参数', /* 当前回调验证订单
|
||||
test('getOrders 序列化账号和状态筛选参数', /* 当前回调验证订单查询筛选参数分支。 */ async () => {
|
||||
// fetchMock 是订单筛选请求的网络替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ data: [], total: 0 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await getOrders('account-1', 'pending_ship');
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('cookie_id=account-1');
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('status=pending_ship');
|
||||
});
|
||||
|
||||
test('paid orders are normalized to pending shipment', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ data: [{ order_id: 'o-paid', order_status: 'paid' }] })));
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse({ data: [{ order_id: 'o-paid', order_status: 'paid' }] })));
|
||||
const result = await getOrders(); /* result 表示处理结果。 */
|
||||
expect(result.data[0].status).toBe('pending_ship');
|
||||
} /* 测试回调验证:paid orders are normalized to pending shipment。 */);
|
||||
|
||||
test('completeQRVerification sends only the immutable target account', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, account_id: 'acc1' })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await completeQRVerification('session-1', 'acc1');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/qr-login/complete-verification/session-1', expect.objectContaining({
|
||||
method: 'POST',
|
||||
@@ -437,7 +501,7 @@ test('completeQRVerification sends only the immutable target account', async ()
|
||||
|
||||
test('deleteItemPublishBatch removes an abandoned preview', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await deleteItemPublishBatch('preview-1');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/items/publish-batches/preview-1', expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
@@ -447,7 +511,7 @@ test('deleteItemPublishBatch removes an abandoned preview', async () => {
|
||||
|
||||
test('publishItem allows virtual publishing without an optional location', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await publishItem({
|
||||
cookie_id: 'acc1',
|
||||
title: '虚拟商品',
|
||||
@@ -462,7 +526,7 @@ test('publishItem allows virtual publishing without an optional location', async
|
||||
} /* 测试回调验证:publishItem allows virtual publishing without an optional location。 */);
|
||||
|
||||
test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse([{
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
item_title: '普通商品',
|
||||
@@ -493,7 +557,7 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
|
||||
test('getItems forwards the selected account filter', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([])); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await getItems('account-2');
|
||||
|
||||
@@ -504,7 +568,7 @@ test('getItems forwards the selected account filter', async () => {
|
||||
} /* 测试回调验证:getItems forwards the selected account filter。 */);
|
||||
|
||||
test('getSystemSettings normalizes numeric renewal retention', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse({
|
||||
ai_model: 'qwen-plus',
|
||||
renewal_log_retention_days: 'invalid',
|
||||
})));
|
||||
@@ -517,7 +581,7 @@ test('getSystemSettings normalizes numeric renewal retention', async () => {
|
||||
// getSystemSettings 脱敏响应测试验证客户端只接收敏感配置状态。
|
||||
test('getSystemSettings keeps only sensitive configuration markers', /* 当前回调验证脱敏设置归一化。 */ async () => {
|
||||
// fetchMock 返回服务端的脱敏设置视图,不包含任何敏感明文。
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse({
|
||||
ai_api_key_configured: 'true',
|
||||
smtp_password_configured: 'false',
|
||||
})));
|
||||
@@ -531,7 +595,7 @@ test('getSystemSettings keeps only sensitive configuration markers', /* 当前
|
||||
|
||||
test('logout calls backend session invalidation route', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await logout();
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/session/logout', expect.objectContaining({
|
||||
@@ -543,7 +607,7 @@ test('logout calls backend session invalidation route', async () => {
|
||||
|
||||
test('account cookie APIs include login_method when provided', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true })) /* 模拟取消操作的成功响应。 */); /* fetchMock 是本测试替代浏览器网络层的请求桩。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await addAccount('acc1', 'unb=acc1', 'qr_scan');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/accounts', expect.objectContaining({
|
||||
@@ -570,7 +634,7 @@ test('account cookie APIs include login_method when provided', async () => {
|
||||
|
||||
test('account editor settings use one aggregate request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await updateAccountSettings('acc1', {
|
||||
remark: 'main', auto_confirm: false, pause_duration: 5,
|
||||
username: 'user', show_browser: true, channel_ids: [1, 2],
|
||||
@@ -584,7 +648,7 @@ test('account editor settings use one aggregate request', async () => {
|
||||
} /* 测试回调验证:account editor settings use one aggregate request。 */);
|
||||
|
||||
test('getAccountDetails normalizes show_browser and never exposes password', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse([{
|
||||
id: 'acc1',
|
||||
enabled: true,
|
||||
auto_confirm: true,
|
||||
@@ -616,7 +680,7 @@ test('列表 API 将 null 和历史 data 包裹统一为空数组', async () =>
|
||||
.mockResolvedValueOnce(jsonResponse({ data: null }))
|
||||
.mockResolvedValueOnce(jsonResponse(null))
|
||||
.mockResolvedValueOnce(jsonResponse({ data: null }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await expect(getAccountDetails()).resolves.toEqual([]);
|
||||
await expect(getItems()).resolves.toEqual([]);
|
||||
@@ -631,7 +695,7 @@ test('列表 API 接受历史命名包裹对象并保持具名 UI 结果', async
|
||||
.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);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await expect(getOrders()).resolves.toMatchObject({ data: [{ id: 'o-wrap', status: 'pending_ship' }] });
|
||||
await expect(getItems()).resolves.toMatchObject([{ id: 'a1-i1' }]);
|
||||
@@ -642,7 +706,7 @@ test('列表 API 接受历史命名包裹对象并保持具名 UI 结果', async
|
||||
test('getAccountDetails 归一化头像地址并保留非法地址', /* 当前回调验证头像缓存参数和 URL 兼容边界。 */ async () => {
|
||||
// windowStub 是头像 URL 解析使用的浏览器位置替身。
|
||||
vi.stubGlobal('window', { location: { origin: 'http://localhost' } });
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse([
|
||||
{ id: 'acc1', enabled: true, avatar_url: 'https://avatar.alicdn.com/avatar.jpg' },
|
||||
{ id: 'acc2', enabled: true, avatar_url: 'https://avatar.example.com/avatar.jpg' },
|
||||
{ id: 'acc3', enabled: true, avatar_url: 'http://[invalid' },
|
||||
@@ -656,7 +720,7 @@ test('getAccountDetails 归一化头像地址并保留非法地址', /* 当前
|
||||
|
||||
test('updateAccountLoginInfo sends exactly provided fields', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateAccountLoginInfo('acc1', { username: 'login-user', show_browser: false });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/accounts/acc1/login-info', expect.objectContaining({
|
||||
@@ -671,7 +735,7 @@ test('updateAccountLoginInfo sends exactly provided fields', async () => {
|
||||
|
||||
test('updateAccountLoginInfo can request explicit password clearing', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateAccountLoginInfo('acc1', { username: 'login-user', clear_password: true, show_browser: false });
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
@@ -683,7 +747,7 @@ test('updateAccountLoginInfo can request explicit password clearing', async () =
|
||||
|
||||
test('updateItem sends only the fields selected by the editor', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateItem('acc1', 'item1', { item_title: '改名商品' });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/items/acc1/item1', expect.objectContaining({
|
||||
@@ -700,7 +764,7 @@ test('password login service uses upstream-compatible routes', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid', status: 'processing' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ status: 'success', account_id: 'acc1', cookie_count: 2 }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await passwordLogin({ account_id: 'acc1', account: 'u', password: 'p' });
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/password-login', expect.objectContaining({
|
||||
@@ -727,7 +791,7 @@ test('账号编辑子模块请求支持取消过期响应', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ can_open_long_login: true, enabled: false }))
|
||||
.mockResolvedValueOnce(jsonResponse({ ai_enabled: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
const controller = new AbortController(); /* controller 表示controller。 */
|
||||
|
||||
await getLongLoginSettings('acc1', { signal: controller.signal });
|
||||
@@ -740,7 +804,7 @@ test('账号编辑子模块请求支持取消过期响应', async () => {
|
||||
} /* 测试回调验证:账号编辑子模块请求支持取消过期响应。 */);
|
||||
|
||||
test('getShippingRules exposes buyer reviewed gift rules as automation rules', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
stubContractFetch(vi.fn().mockResolvedValue(jsonResponse([{
|
||||
id: 12,
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
@@ -784,7 +848,7 @@ test('getReplyRules labels keyword matching according to engine contains behavio
|
||||
type: 'image',
|
||||
image_url: 'https://img.example/reply.png',
|
||||
}])); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
const rules = await getReplyRules('acc1'); /* rules 表示规则集合。 */
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/reply-rules/acc1/typed', expect.objectContaining({ method: 'GET' }));
|
||||
@@ -808,17 +872,17 @@ test('getCards 解析 JSON 和损坏 JSON 的卡密接口配置', /* 当前回
|
||||
{ id: 1, name: '有效', api_config: '{"endpoint":"https://example.com"}' },
|
||||
{ id: 2, name: '损坏', api_config: '{broken' },
|
||||
]));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// cards 是卡密配置归一化后的库存列表。
|
||||
const cards = await getCards();
|
||||
expect(cards[0].api_config).toEqual({ endpoint: 'https://example.com' });
|
||||
expect(cards[0].api_config).toEqual({ endpoint: 'https://example.com', content_type: 'application/json' });
|
||||
expect(cards[1].api_config).toBeUndefined();
|
||||
});
|
||||
|
||||
test('getCards 将后端空响应归一化为空列表', /* 当前回调防止空卡密响应阻断自动化规则账号加载。 */ async () => {
|
||||
// fetchMock 模拟兼容后端返回 JSON null 的卡密列表响应。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(null));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await expect(getCards()).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
@@ -827,7 +891,7 @@ test('默认回复 API 补齐空字段默认值', /* 当前回调验证默认回
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ enabled: false }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await expect(getDefaultReply('account-1')).resolves.toEqual({ cookie_id: 'account-1', enabled: false, reply_content: '', reply_once: false, reply_image_url: '' });
|
||||
await updateDefaultReply('account-1', {});
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ enabled: false, reply_content: '', reply_once: false, reply_image_url: '' });
|
||||
@@ -835,7 +899,7 @@ test('默认回复 API 补齐空字段默认值', /* 当前回调验证默认回
|
||||
|
||||
test('updateReplyRule preserves keyword image metadata when saving text edits', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateReplyRule({ id: '42', keyword: '发货', reply_content: '稍后安排', item_id: 'item-1' }, 'acc1');
|
||||
|
||||
@@ -851,7 +915,7 @@ test('updateReplyRule preserves keyword image metadata when saving text edits',
|
||||
|
||||
test('updateReplyRule clears stale content when switching reply type', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateReplyRule({ id: '42', keyword: '发货', type: 'image', image_url: 'https://img.example/new.png' }, 'acc1');
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
@@ -861,7 +925,7 @@ test('updateReplyRule clears stale content when switching reply type', async ()
|
||||
|
||||
test('deleteReplyRule deletes one stable keyword row instead of replacing the list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await deleteReplyRule('42', 'acc1');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
@@ -873,7 +937,7 @@ test('deleteReplyRule deletes one stable keyword row instead of replacing the li
|
||||
|
||||
test('createNotificationChannel persists email recipient as to_email config', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await createNotificationChannel({
|
||||
name: '邮件通知',
|
||||
@@ -897,7 +961,7 @@ test('createNotificationChannel persists email recipient as to_email config', as
|
||||
|
||||
test('createNotificationChannel allows email channel to rely on system SMTP settings', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await createNotificationChannel({
|
||||
name: '邮件通知',
|
||||
@@ -916,7 +980,7 @@ test('createNotificationChannel allows email channel to rely on system SMTP sett
|
||||
|
||||
test('updateNotificationChannel supports partial enabled updates', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateNotificationChannel('7', { enabled: false });
|
||||
|
||||
@@ -932,7 +996,7 @@ test('updateNotificationChannel supports partial enabled updates', async () => {
|
||||
test('updateNotificationChannel serializes config and event types', /* 当前回调验证通知渠道请求体序列化。 */ async () => {
|
||||
// fetchMock 是通知渠道更新接口的网络替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await updateNotificationChannel('7', { config: { server_url: 'https://example.com' }, event_types: ['system_error'] });
|
||||
// body 是通知渠道更新请求体。
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
@@ -946,14 +1010,14 @@ test('getMessageNotifications 展开数组并忽略非法绑定值', /* 当前
|
||||
'account-1': [{ channel_id: 1, channel_name: '邮件', enabled: true }],
|
||||
'account-2': null,
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await expect(getMessageNotifications()).resolves.toEqual({ success: true, data: [{ cookie_id: 'account-1', channel_id: 1, channel_name: '邮件', enabled: true }] });
|
||||
});
|
||||
|
||||
test('publishItem 序列化图片和地点字段', /* 当前回调验证商品发布 multipart 请求体。 */ async () => {
|
||||
// fetchMock 是商品发布上传接口的网络替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// image 是待上传的商品图片文件。
|
||||
const image = new File(['image'], 'item.png', { type: 'image/png' });
|
||||
await publishItem({ cookie_id: 'account-1', title: '商品', description: '描述', price: '10', quantity: 2, postage_mode: 'free', images: [image], location: { area: '区域', city: '城市', division_id: '1', longitude: 120, latitude: 30, poi_id: 'poi-1', poi_name: '地点', province: '省' } });
|
||||
@@ -970,7 +1034,7 @@ test('通知事件字段支持 JSON 数组和分隔符格式', /* 当前回调
|
||||
{ id: 2, name: '分隔符', type: 'bark', config: '{}', event_types: 'system_error, order_paid; buyer_reviewed', enabled: true },
|
||||
{ id: 3, name: '数组', type: 'bark', config: '{}', event_types: ['system_error'], enabled: true },
|
||||
]));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
// result 是通知事件字段解析后的渠道列表。
|
||||
const result = await getNotificationChannels();
|
||||
expect(result.data?.[0].event_types).toEqual(['system_error', 'order_paid']);
|
||||
@@ -980,7 +1044,7 @@ test('通知事件字段支持 JSON 数组和分隔符格式', /* 当前回调
|
||||
|
||||
test('updateShippingRule posts buyer reviewed gift payload to automation-rules', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 1 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
cookie_id: 'cookie-1',
|
||||
@@ -1018,7 +1082,7 @@ test('updateShippingRule posts buyer reviewed gift payload to automation-rules',
|
||||
|
||||
test('updateShippingRule posts every matching card action before confirm shipment', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 3 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
cookie_id: 'cookie-1',
|
||||
@@ -1071,7 +1135,7 @@ test('updateShippingRule posts every matching card action before confirm shipmen
|
||||
|
||||
test('updateShippingRule preserves text actions while editing card variants', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 4 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
id: '4',
|
||||
@@ -1093,7 +1157,7 @@ test('updateShippingRule preserves text actions while editing card variants', as
|
||||
|
||||
test('updateShippingRule posts review request text action without card requirement', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 2 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
cookie_id: 'cookie-1',
|
||||
@@ -1128,7 +1192,7 @@ const runVersionedSessionAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, authenticated: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, authenticated: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, authenticated: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await login({ username: 'admin', password: 'pw' });
|
||||
await initializeAdmin('long-password');
|
||||
@@ -1150,7 +1214,7 @@ const runVersionedAccountAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse([{ id: 'acc1', enabled: true, remark: '主账号' }]))
|
||||
.mockResolvedValueOnce(jsonResponse({ acc1: { state: 'error', connected: false, failures: 0, updated_at: '' } }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await getAccountDetails();
|
||||
await getAccountRuntimeStatuses();
|
||||
@@ -1174,7 +1238,7 @@ const runVersionedAccountSettingsAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, paused_until: 0, paused: false }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await updateAccountSettings('acc1', { remark: '主账号' });
|
||||
await getLongLoginSettings('acc1');
|
||||
@@ -1202,7 +1266,7 @@ const runVersionedOrderAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ data: [{ order_id: 'order-1', order_status: 'pending_ship' }], total: 1 }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, order_id: 'order-1', data: { order_id: 'order-1', order_status: 'pending_ship' } }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await getOrders();
|
||||
await getOrderDetail('order-1');
|
||||
@@ -1221,7 +1285,7 @@ const runVersionedOrderRefreshAPITest = async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await syncSingleOrder('order-1');
|
||||
await manualShipOrder(['order-1'], 'status_only');
|
||||
@@ -1241,7 +1305,7 @@ const runVersionedItemAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, item_id: 'item-1' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await getItems('acc1');
|
||||
await getItemDetail('acc1', 'item-1');
|
||||
@@ -1274,7 +1338,7 @@ const runVersionedItemBatchAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, status: 'canceled' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, batch_id: 'batch-1' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await syncItemsFromAccount('acc1');
|
||||
await recommendPublishCategory('acc1', '资料');
|
||||
@@ -1337,7 +1401,7 @@ const runVersionedSettingsCardNotificationAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ channel_ids: [] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await getSystemSettings();
|
||||
await updateSystemSettings({ theme_color: 'blue' });
|
||||
@@ -1406,7 +1470,7 @@ const runVersionedChatTaskAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ account_id: 'acc1' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ account_id: 'acc1' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await getChatSessionPage('acc1', 3, undefined, true);
|
||||
await getChatMessagePage('acc1', 'chat-1', 4, 9);
|
||||
@@ -1446,7 +1510,7 @@ const runVersionedReplyAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await getReplyRules('acc1');
|
||||
await updateReplyRule({ id: '42', keyword: '发货', reply_content: '稍后安排' }, 'acc1');
|
||||
@@ -1479,7 +1543,7 @@ const runVersionedAdminAnalyticsAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ total_cookies: 1, active_cookies: 1, total_cards: 0, available_card_stock: 0, total_keywords: 0, total_orders: 0 }))
|
||||
.mockResolvedValueOnce(jsonResponse({ revenue_stats: {}, daily_stats: [], status_stats: [], city_stats: [], item_stats: [] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ orders: [], total: 0, page: 1, page_size: 500, truncated: false }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await getAdminStats();
|
||||
await getDashboardStats();
|
||||
@@ -1500,7 +1564,7 @@ const runVersionedQRLoginAPITest = async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'session-1', qr_code_url: 'data:image/png;base64,abc' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ status: 'waiting', session_id: 'session-1' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
await generateQRLogin();
|
||||
await checkQRLoginStatus('session-1');
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/qr-login/generate', expect.objectContaining({ method: 'POST' }));
|
||||
@@ -1528,7 +1592,7 @@ const runVersionedRemainingAPITest = async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ runs: [], pending_tasks: [] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
stubContractFetch(fetchMock);
|
||||
|
||||
await changePassword('old-password', 'new-password');
|
||||
await updateLoginCredentials({ current_password: 'old-password', new_username: 'new-user' });
|
||||
|
||||
@@ -2,11 +2,15 @@ import {
|
||||
Card,
|
||||
CardAppendResponse,
|
||||
CardBatchResponse,
|
||||
CardMutation,
|
||||
CardAPITestResult,
|
||||
CardAPIConfigInput,
|
||||
MutationIDResponse,OperationResponse
|
||||
} from '../../../shared/api-contract/cards';
|
||||
import { del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
} from './models';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { contractClient, contractMultipartBody, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { collectionFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/cards';
|
||||
export type * from './models';
|
||||
// Cards
|
||||
// normalizeCard 归一化卡密数据。
|
||||
const normalizeCard = (item: any): Card => {
|
||||
@@ -19,43 +23,76 @@ const normalizeCard = (item: any): Card => {
|
||||
apiConfig = undefined;
|
||||
}
|
||||
}
|
||||
if (apiConfig && typeof apiConfig === 'object' && apiConfig.timeout_seconds === undefined && apiConfig.timeout !== undefined) {
|
||||
// normalizedTimeout 将历史 timeout 字段迁移到新版摘要字段。
|
||||
apiConfig.timeout_seconds = Number(apiConfig.timeout) || 10;
|
||||
}
|
||||
if (apiConfig && typeof apiConfig === 'object' && !apiConfig.content_type) {
|
||||
apiConfig.content_type = 'application/json';
|
||||
}
|
||||
return {...item, api_config: apiConfig || undefined} as Card;
|
||||
};
|
||||
|
||||
// cardPayload 卡密请求载荷,用于当前 API 处理流程。
|
||||
const cardPayload = (data: Partial<Card>): Record<string, unknown> => ({
|
||||
...data,
|
||||
api_config: data.api_config ? JSON.stringify(data.api_config) : '',
|
||||
// parseTemplateJSON 将表单中的 JSON 模板转换为请求对象,空模板交给服务端执行保留语义。
|
||||
const parseTemplateJSON = (value: unknown): Record<string, unknown> | undefined => {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) return value as Record<string, unknown>;
|
||||
if (typeof value !== 'string' || !value.trim()) return undefined;
|
||||
// parsed 保存表单 JSON 文本解析后的未知值,随后只接受对象。
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('请求头和请求参数必须是 JSON 对象');
|
||||
return parsed as Record<string, unknown>;
|
||||
};
|
||||
|
||||
// cardPayload 将 feature 表单映射为新版具名 API 请求载荷,并兼容旧字符串配置。
|
||||
const cardPayload = (data: CardMutation) => ({
|
||||
name: data.name,
|
||||
type: data.type,
|
||||
api_config: typeof data.api_config === 'string' ? data.api_config : data.api_config ? {
|
||||
...data.api_config,
|
||||
headers: parseTemplateJSON(data.api_config.headers),
|
||||
params: parseTemplateJSON(data.api_config.params),
|
||||
body: parseTemplateJSON(data.api_config.body),
|
||||
content_type: data.api_config.content_type || 'application/json',
|
||||
} : undefined,
|
||||
text_content: data.text_content,
|
||||
data_content: data.data_content,
|
||||
image_url: data.image_url,
|
||||
description: data.description,
|
||||
enabled: data.enabled,
|
||||
delay_seconds: data.delay_seconds,
|
||||
is_multi_spec: data.is_multi_spec,
|
||||
spec_name: data.spec_name,
|
||||
spec_value: data.spec_value,
|
||||
});
|
||||
|
||||
// getCards 读取卡密列表。
|
||||
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const res = await get<unknown>('/api/v1/cards', undefined, options);
|
||||
const res = await runContractRequest(/* signal 控制卡券列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/cards', { signal }), options) as unknown;
|
||||
// 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));
|
||||
export const createCard = async (data: CardMutation): Promise<MutationIDResponse> => {
|
||||
return runContractRequest(/* signal 控制卡券创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards', { body: cardPayload(data), signal }));
|
||||
};
|
||||
|
||||
// updateCard 更新卡密组。
|
||||
export const updateCard = async (cardId: string | number, data: Partial<Card>): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/cards/${cardId}`, cardPayload(data));
|
||||
export const updateCard = async (cardId: string | number, data: CardMutation): Promise<OperationResponse> => {
|
||||
return runContractRequest(/* signal 控制卡券更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/cards/{card_id}', { params: { path: { card_id: String(cardId) } }, body: cardPayload(data), signal }));
|
||||
};
|
||||
|
||||
// deleteCard 删除卡密组。
|
||||
export const deleteCard = async (cardId: string | number): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/cards/${cardId}`);
|
||||
return runContractRequest(/* signal 控制卡券删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/cards/{card_id}', { params: { path: { card_id: String(cardId) } }, signal }));
|
||||
};
|
||||
|
||||
// getCardDetails 读取卡密组详情。
|
||||
export const getCardDetails = async (cardId: string | number): Promise<Card> => {
|
||||
// card 卡密详情,用于当前 API 处理流程。
|
||||
const card = await get<Card>(`/api/v1/cards/${cardId}/details`);
|
||||
const card = await runContractRequest(/* signal 控制卡券详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/cards/{card_id}/details', { params: { path: { card_id: String(cardId) } }, signal }));
|
||||
return normalizeCard(card);
|
||||
};
|
||||
|
||||
@@ -69,10 +106,18 @@ export const batchCreateCards = async (file: File, options?: RequestControlOptio
|
||||
// 此处只收紧 TypeScript 响应契约。
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
return postForm('/api/v1/cards/batch', body, options);
|
||||
return runContractRequest(/* signal 控制卡券批量上传的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/batch', { body: contractMultipartBody(body), signal }), 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);
|
||||
return runContractRequest(/* signal 控制卡券追加数据请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/{card_id}/append-data', { params: { path: { card_id: String(cardId) } }, body: { content }, signal }), options);
|
||||
};
|
||||
|
||||
// testCardAPI 发送一次临时 API 配置测试请求,不保存卡密配置。
|
||||
export const testCardAPI = async (data: CardAPIConfigInput): Promise<CardAPITestResult> => {
|
||||
return runContractRequest(/* signal 控制 API 测试请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/test-api', {
|
||||
body: { api_config: cardPayload({ name: '', type: 'api', api_config: data }).api_config } as never,
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect,test } from 'vitest';
|
||||
import type { Card } from '../../../shared/api-contract/cards';
|
||||
import type { Card } from './api';
|
||||
import { canSubmitAppend,filterCards,isCurrentCardRequest,previewAppendContent } from './batchState';
|
||||
|
||||
// cards 是卡密筛选测试使用的最小卡密组列表。
|
||||
|
||||
@@ -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 '../../../shared/api-contract/cards';
|
||||
import type { Card } from './api';
|
||||
import { useCardActions } from './cardActions';
|
||||
|
||||
// cardActionMocks 保存卡密动作 Hook 测试使用的 API 替身。
|
||||
@@ -26,8 +26,6 @@ const cardFixture: Card = {
|
||||
description: '测试库存',
|
||||
enabled: true,
|
||||
delay_seconds: 0,
|
||||
created_at: '2026-08-15T00:00:00Z',
|
||||
updated_at: '2026-08-15T00:00:00Z',
|
||||
};
|
||||
|
||||
// textCardFixture 表示用于筛选和新增测试的文本类型卡密组。
|
||||
@@ -93,6 +91,42 @@ describe('useCardActions 卡密动作协调器', /* 当前回调验证卡密筛
|
||||
expect(hook.result.current.showAddModal).toBe(false);
|
||||
});
|
||||
|
||||
test('编辑 API 卡替换空模板时明确清空而不是保留旧模板', /* 当前回调验证敏感模板替换空值的显式清除语义。 */ async () => {
|
||||
// apiCard 保存只含脱敏摘要的 API 卡密组。
|
||||
const apiCard: Card = {
|
||||
...cardFixture,
|
||||
id: 4,
|
||||
name: '接口卡',
|
||||
type: 'api',
|
||||
api_config: {
|
||||
url: 'https://example.test/card',
|
||||
method: 'POST',
|
||||
timeout_seconds: 10,
|
||||
content_type: 'application/json',
|
||||
headers_configured: true,
|
||||
params_configured: true,
|
||||
retry_enabled: false,
|
||||
ready: true,
|
||||
},
|
||||
};
|
||||
// loadCards 是 API 卡编辑完成后的刷新替身。
|
||||
const loadCards = vi.fn().mockResolvedValue(undefined);
|
||||
// hook 是注入 API 卡测试数据的动作 Hook。
|
||||
const hook = renderHook(/* hookFactory 渲染注入 API 卡的动作 Hook。 */ () => useCardActions({ cards: [apiCard], loadCards }));
|
||||
act(/* editAction 打开 API 卡编辑表单。 */ () => hook.result.current.handleEdit(apiCard));
|
||||
act(/* templateAction 将两个敏感模板设置为显式替换。 */ () => hook.result.current.setEditForm(/* formUpdater 清空替换模板的表单值。 */ current => ({
|
||||
...current,
|
||||
api_headers_action: 'replace',
|
||||
api_params_action: 'replace',
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
})));
|
||||
await act(/* saveAction 提交 API 卡编辑并等待刷新完成。 */ async () => hook.result.current.handleSaveEdit());
|
||||
expect(cardActionMocks.updateCard).toHaveBeenCalledWith(4, expect.objectContaining({
|
||||
api_config: expect.objectContaining({ headers: {}, params: {} }),
|
||||
}));
|
||||
});
|
||||
|
||||
test('删除取消、删除失败和状态切换失败均不制造虚假成功', /* 当前回调验证卡密删除和启停异常分支。 */ async () => {
|
||||
// actionContext 保存卡密删除 Hook 和库存刷新替身。
|
||||
const { hook, loadCards } = createCardHook();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback,useMemo,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { Card } from './api';
|
||||
import type { Card,CardMutation } from './api';
|
||||
import { createCard,deleteCard,updateCard } from './api';
|
||||
import { filterCards } from './batchState';
|
||||
import type { AddCardForm,EditCardForm } from './types';
|
||||
@@ -16,6 +16,10 @@ export const emptyAddForm = (): AddCardForm => ({
|
||||
api_timeout: 10,
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
api_content_type: 'application/json',
|
||||
api_body: '',
|
||||
api_response_path: '',
|
||||
api_retry_enabled: false,
|
||||
});
|
||||
|
||||
// CardActionsOptions 描述卡密动作协调器依赖的库存状态和刷新操作。
|
||||
@@ -110,9 +114,15 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
type: card.type || 'text',
|
||||
api_url: card.api_config?.url || '',
|
||||
api_method: card.api_config?.method || 'GET',
|
||||
api_timeout: card.api_config?.timeout || 10,
|
||||
api_headers: card.api_config?.headers || '',
|
||||
api_params: card.api_config?.params || '',
|
||||
api_timeout: card.api_config?.timeout_seconds || 10,
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
api_content_type: card.api_config?.content_type || 'application/json',
|
||||
api_body: '',
|
||||
api_response_path: card.api_config?.response_path || '',
|
||||
api_retry_enabled: card.api_config?.retry_enabled || false,
|
||||
api_headers_action: 'retain',
|
||||
api_params_action: 'retain',
|
||||
text_content: card.text_content || '',
|
||||
data_content: card.data_content || '',
|
||||
image_url: card.image_url || '',
|
||||
@@ -136,7 +146,7 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
}
|
||||
try {
|
||||
// updateData 保存映射到卡密更新接口的字段。
|
||||
const updateData: Partial<Card> = {
|
||||
const updateData: CardMutation = {
|
||||
name: editForm.name.trim(),
|
||||
type: editForm.type,
|
||||
description: editForm.description?.trim(),
|
||||
@@ -147,9 +157,15 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
updateData.api_config = {
|
||||
url: editForm.api_url?.trim() || '',
|
||||
method: editForm.api_method || 'GET',
|
||||
timeout: editForm.api_timeout || 10,
|
||||
headers: editForm.api_headers?.trim() || undefined,
|
||||
params: editForm.api_params?.trim() || undefined,
|
||||
timeout_seconds: editForm.api_timeout || 10,
|
||||
headers: editForm.api_headers_action === 'clear' ? undefined : editForm.api_headers_action === 'replace' && !editForm.api_headers?.trim() ? {} : editForm.api_headers?.trim() || undefined,
|
||||
params: editForm.api_params_action === 'clear' ? undefined : editForm.api_params_action === 'replace' && !editForm.api_params?.trim() ? {} : editForm.api_params?.trim() || undefined,
|
||||
content_type: editForm.api_content_type || 'application/json',
|
||||
body: editForm.api_body?.trim() || undefined,
|
||||
headers_action: editForm.api_headers_action || 'retain',
|
||||
params_action: editForm.api_params_action || 'retain',
|
||||
response_path: editForm.api_response_path?.trim() || undefined,
|
||||
retry_enabled: editForm.api_retry_enabled || false,
|
||||
};
|
||||
} else if (editForm.type === 'text') {
|
||||
updateData.text_content = editForm.text_content?.trim() || '';
|
||||
@@ -191,7 +207,7 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
}
|
||||
try {
|
||||
// payload 保存新增卡密组的接口载荷。
|
||||
const payload: Partial<Card> = {
|
||||
const payload: CardMutation = {
|
||||
name: addForm.name.trim(),
|
||||
type: addForm.type,
|
||||
description: addForm.description.trim(),
|
||||
@@ -205,9 +221,13 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
payload.api_config = {
|
||||
url: addForm.content.trim(),
|
||||
method: addForm.api_method,
|
||||
timeout: addForm.api_timeout,
|
||||
timeout_seconds: addForm.api_timeout,
|
||||
headers: addForm.api_headers.trim() || undefined,
|
||||
params: addForm.api_params.trim() || undefined,
|
||||
content_type: addForm.api_content_type,
|
||||
body: addForm.api_body.trim() || undefined,
|
||||
response_path: addForm.api_response_path.trim() || undefined,
|
||||
retry_enabled: addForm.api_retry_enabled,
|
||||
};
|
||||
}
|
||||
await createCard(payload);
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
import { Loader2, Play, Plus, Trash2 } from 'lucide-react';
|
||||
import { useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import type { CardAPITestResult } from '../models';
|
||||
|
||||
// APIRequestMethod 是 API 发货请求支持的 HTTP 方法。
|
||||
export type APIRequestMethod = 'GET' | 'POST';
|
||||
|
||||
// APISecretAction 描述编辑敏感模板时对服务端已保存值的处理方式。
|
||||
export type APISecretAction = 'retain' | 'replace' | 'clear';
|
||||
|
||||
// APIKeyValueRow 是 Postman 风格键值编辑器中的一行表单数据。
|
||||
export interface APIKeyValueRow {
|
||||
// key 是请求头、查询参数或表单字段名称。
|
||||
key: string;
|
||||
// value 是字段值;动态变量会以文本形式保留到服务端替换。
|
||||
value: string;
|
||||
}
|
||||
|
||||
// APIRequestBuilderProps 描述 API 请求编辑器的受控字段和保存动作。
|
||||
export interface APIRequestBuilderProps {
|
||||
// url 是远端 API 地址。
|
||||
url: string;
|
||||
// method 是远端 API 请求方法。
|
||||
method: APIRequestMethod;
|
||||
// timeout 是单次远端请求的超时秒数。
|
||||
timeout: number;
|
||||
// headers 是请求头 JSON 文本,组件以键值行展示。
|
||||
headers: string;
|
||||
// params 是 URL 查询参数 JSON 文本,组件以键值行展示。
|
||||
params: string;
|
||||
// contentType 是 POST 请求正文的 Content-Type。
|
||||
contentType: string;
|
||||
// body 是 JSON 正文或非 JSON 正文的键值 JSON 文本。
|
||||
body: string;
|
||||
// responsePath 是成功响应中的卡密提取路径。
|
||||
responsePath: string;
|
||||
// retryEnabled 表示是否启用带幂等键的重试。
|
||||
retryEnabled: boolean;
|
||||
// headersAction 是编辑时请求头敏感模板的三态处理方式。
|
||||
headersAction?: APISecretAction;
|
||||
// paramsAction 是编辑时查询参数敏感模板的三态处理方式。
|
||||
paramsAction?: APISecretAction;
|
||||
// onChange 更新指定 API 配置字段。
|
||||
onChange: (field: APIRequestField, value: string | number | boolean) => void;
|
||||
// onTest 使用当前配置执行临时测试请求。
|
||||
onTest?: () => Promise<CardAPITestResult>;
|
||||
}
|
||||
|
||||
// APIRequestField 是 APIRequestBuilder 可更新字段的联合类型。
|
||||
export type APIRequestField =
|
||||
| 'url'
|
||||
| 'method'
|
||||
| 'timeout'
|
||||
| 'headers'
|
||||
| 'params'
|
||||
| 'contentType'
|
||||
| 'body'
|
||||
| 'responsePath'
|
||||
| 'retryEnabled'
|
||||
| 'headersAction'
|
||||
| 'paramsAction';
|
||||
|
||||
// APITestState 保存 API 测试请求的加载状态、非敏感诊断结果与请求错误。
|
||||
interface APITestState {
|
||||
// loading 表示当前是否正在等待远端测试响应。
|
||||
loading: boolean;
|
||||
// result 是远端完成请求后返回的状态和响应结构诊断。
|
||||
result?: CardAPITestResult;
|
||||
// error 是本地请求、超时或配置错误的用户可见提示。
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// contentTypes 保存常用且不依赖文件上传的请求正文类型。
|
||||
const contentTypes = [
|
||||
{ value: 'application/json', label: 'JSON(application/json)' },
|
||||
{ value: 'application/x-www-form-urlencoded', label: '表单键值(x-www-form-urlencoded)' },
|
||||
{ value: 'text/plain', label: '纯文本(text/plain)' },
|
||||
{ value: 'application/xml', label: 'XML(application/xml)' },
|
||||
];
|
||||
|
||||
// isJSONContentType 判断正文类型是否应该使用 JSON 编辑器。
|
||||
const isJSONContentType = (contentType: string): boolean => contentType.toLowerCase().includes('json');
|
||||
|
||||
// rowsFromJSON 将已保存的 JSON 对象转成适合键值编辑器展示的行。
|
||||
const rowsFromJSON = (value: string): APIKeyValueRow[] => {
|
||||
if (!value.trim()) return [{ key: '', value: '' }];
|
||||
try {
|
||||
// parsed 是配置模板解析后的未知 JSON 值。
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return [{ key: '', value: '' }];
|
||||
// entries 是对象中每个字段的键和值。
|
||||
const entries = Object.entries(parsed as Record<string, unknown>);
|
||||
if (entries.length === 0) return [{ key: '', value: '' }];
|
||||
return entries.map(/* entry 保存当前对象字段的键和值。 */ entry => {
|
||||
// key、entryValue 分别是当前模板字段名称和字段值。
|
||||
const [key, entryValue] = entry;
|
||||
return { key, value: typeof entryValue === 'string' ? entryValue : JSON.stringify(entryValue) };
|
||||
});
|
||||
} catch {
|
||||
return [{ key: '', value: value.trim() }];
|
||||
}
|
||||
};
|
||||
|
||||
// rowsToJSON 将键值行序列化为服务端使用的 JSON 对象文本。
|
||||
const rowsToJSON = (rows: APIKeyValueRow[]): string => {
|
||||
// object 是过滤空键后待提交的键值对象。
|
||||
const object = rows.reduce<Record<string, string>>(/* reduceCallback 汇总非空键名的模板字段。 */ (result, row) => {
|
||||
// key 是当前行清理空白后的字段名称。
|
||||
const key = row.key.trim();
|
||||
if (key) result[key] = row.value;
|
||||
return result;
|
||||
}, {});
|
||||
return JSON.stringify(object);
|
||||
};
|
||||
|
||||
// KeyValueEditorProps 描述一组 Postman 风格键值行编辑器。
|
||||
interface KeyValueEditorProps {
|
||||
// label 是当前键值区块的可见标题。
|
||||
label: string;
|
||||
// value 是当前键值对象的 JSON 文本。
|
||||
value: string;
|
||||
// placeholder 是第一行输入的示例文本。
|
||||
placeholder: string;
|
||||
// onChange 接收序列化后的键值对象。
|
||||
onChange: (value: string) => void;
|
||||
}
|
||||
|
||||
// KeyValueEditor 渲染可增删的键值对输入行。
|
||||
const KeyValueEditor = ({ label, value, placeholder, onChange }: KeyValueEditorProps) => {
|
||||
// rows 保存当前键值编辑行;空行也必须保留在本地状态中,才能支持连续添加。
|
||||
const [rows, setRows] = useState<APIKeyValueRow[]>(() => rowsFromJSON(value));
|
||||
// lastEmittedValue 记录本组件最近一次提交的 JSON,避免空行序列化为 {} 后被外部同步立即抹掉。
|
||||
const lastEmittedValue = useRef(value);
|
||||
|
||||
// syncRows 在父表单从外部载入新模板时重置编辑行;本组件自己的更新不重复覆盖空行。
|
||||
useEffect(/* syncRowsEffect 同步外部模板变更并保留本地新增空行。 */ () => {
|
||||
if (value !== lastEmittedValue.current) {
|
||||
setRows(rowsFromJSON(value));
|
||||
lastEmittedValue.current = value;
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
// emitRows 保存本地键值行并通知父表单更新敏感模板 JSON。
|
||||
const emitRows = (nextRows: APIKeyValueRow[]) => {
|
||||
// serialized 是当前键值行转成的服务端 JSON 对象文本。
|
||||
const serialized = rowsToJSON(nextRows);
|
||||
setRows(nextRows);
|
||||
lastEmittedValue.current = serialized;
|
||||
onChange(serialized);
|
||||
};
|
||||
|
||||
// updateRow 修改某一行并把完整对象交回父表单。
|
||||
const updateRow = (index: number, field: keyof APIKeyValueRow, nextValue: string) => {
|
||||
// nextRows 是修改当前字段后的完整键值行列表。
|
||||
const nextRows = rows.map(/* rowUpdater 更新当前键值编辑行。 */ (row, rowIndex) => rowIndex === index ? { ...row, [field]: nextValue } : row);
|
||||
emitRows(nextRows);
|
||||
};
|
||||
|
||||
// addRow 在末尾追加一行空键值输入。
|
||||
const addRow = () => emitRows([...rows, { key: '', value: '' }]);
|
||||
|
||||
// removeRow 删除指定键值行,并确保编辑器始终保留一行可输入内容。
|
||||
const removeRow = (index: number) => emitRows(rows.filter(/* rowFilter 保留未被删除的键值行。 */ (_, rowIndex) => rowIndex !== index));
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-bold text-gray-800">{label}</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addRow}
|
||||
className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs font-bold text-blue-600 transition-colors hover:bg-blue-50"
|
||||
title={`添加${label}字段`}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
添加字段
|
||||
</button>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
|
||||
<div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)_40px] gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 text-[11px] font-bold uppercase tracking-wide text-gray-400">
|
||||
<span>KEY</span>
|
||||
<span>VALUE</span>
|
||||
<span aria-hidden="true" />
|
||||
</div>
|
||||
<div className="divide-y divide-gray-100">
|
||||
{rows.map(/* rowRenderer 渲染当前键值编辑行。 */ (row, index) => (
|
||||
<div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)_40px] items-center gap-2 px-3 py-2" key={`${label}-${index}`}>
|
||||
<input
|
||||
aria-label={`${label}第${index + 1}行键名`}
|
||||
value={row.key}
|
||||
onChange={/* 当前回调更新键值行的字段名称。 */ (event: ChangeEvent<HTMLInputElement>) => updateRow(index, 'key', event.target.value)}
|
||||
placeholder={index === 0 ? placeholder : '键名'}
|
||||
className="min-w-0 border-0 bg-transparent px-1 py-2 font-mono text-sm text-gray-800 outline-none ring-0 placeholder:text-gray-300"
|
||||
/>
|
||||
<input
|
||||
aria-label={`${label}第${index + 1}行值`}
|
||||
value={row.value}
|
||||
onChange={/* 当前回调更新键值行的字段值。 */ (event: ChangeEvent<HTMLInputElement>) => updateRow(index, 'value', event.target.value)}
|
||||
placeholder={index === 0 ? '输入值或动态变量,例如 {order_id}' : '值'}
|
||||
className="min-w-0 border-0 bg-transparent px-1 py-2 font-mono text-sm text-gray-800 outline-none ring-0 placeholder:text-gray-300"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调删除指定键值编辑行。 */ () => removeRow(index)}
|
||||
className="inline-flex h-8 w-8 items-center justify-center rounded-lg text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
||||
title={`删除${label}第${index + 1}行`}
|
||||
aria-label={`删除${label}第${index + 1}行`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// APIRequestBuilder 渲染 API 地址、元数据以及 Headers / Params / Body 三个请求区块。
|
||||
export const APIRequestBuilder = ({
|
||||
url,
|
||||
method,
|
||||
timeout,
|
||||
headers,
|
||||
params,
|
||||
contentType,
|
||||
body,
|
||||
responsePath,
|
||||
retryEnabled,
|
||||
headersAction,
|
||||
paramsAction,
|
||||
onChange,
|
||||
onTest,
|
||||
}: APIRequestBuilderProps) => {
|
||||
// jsonBody 表示当前正文类型是否使用 JSON 文本编辑器。
|
||||
const jsonBody = isJSONContentType(contentType);
|
||||
// testState 保存最近一次 API 测试的加载、结果和错误状态。
|
||||
const [testState, setTestState] = useState<APITestState>({ loading: false });
|
||||
// runTest 触发临时请求并保留结果在当前弹窗中。
|
||||
const runTest = async () => {
|
||||
if (!onTest) return;
|
||||
setTestState({ loading: true });
|
||||
try {
|
||||
setTestState({ loading: false, result: await onTest() });
|
||||
} catch (/* error 表示测试请求的本地错误或共享 HTTP 客户端返回的异常。 */ error) {
|
||||
setTestState({ loading: false, error: error instanceof Error ? error.message : 'API 测试请求失败' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-5 rounded-2xl border border-blue-100 bg-blue-50/40 p-4 sm:p-5">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="font-bold text-gray-900">API 请求配置</h3>
|
||||
<p className="mt-1 text-xs text-gray-500">按 Postman 的请求结构填写,敏感模板只会加密保存在服务端。</p>
|
||||
</div>
|
||||
<span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-bold text-blue-600 shadow-sm">API</span>
|
||||
</div>
|
||||
{onTest && (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="button" onClick={runTest} disabled={testState.loading} className="inline-flex items-center gap-2 rounded-xl bg-gray-900 px-4 py-2.5 text-sm font-bold text-white transition-colors hover:bg-gray-700 disabled:cursor-wait disabled:opacity-60">
|
||||
{testState.loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
测试请求
|
||||
</button>
|
||||
{testState.error && <span className="text-sm font-semibold text-red-600">{testState.error}</span>}
|
||||
{testState.result && (
|
||||
<div className={`w-full rounded-xl border p-3 text-sm ${testState.result.status === 'success' ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'}`}>
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-1 font-semibold">
|
||||
<span>{testState.result.status === 'success' ? '测试成功' : '测试失败'}</span>
|
||||
<span>HTTP 状态:{testState.result.status_code || '网络错误'}</span>
|
||||
<span>响应类型:{testState.result.response_content_type || '未知'}</span>
|
||||
</div>
|
||||
<div className="mt-2 grid gap-1 text-gray-700"><span>响应字段:{testState.result.response_fields.length ? testState.result.response_fields.join('、') : '未识别 JSON 字段'}</span><span>提取结果:{testState.result.extracted_value || '未提取到内容'}</span></div>
|
||||
{testState.result.response_preview && <pre className="mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded-lg bg-white/70 p-2 text-xs text-gray-600">{testState.result.response_preview}</pre>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[minmax(0,1fr)_130px_130px]">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">API 地址</label>
|
||||
<input
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={/* 当前回调更新远端 API 地址。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('url', event.target.value)}
|
||||
className="w-full ios-input rounded-xl px-4 py-3 font-mono text-sm"
|
||||
placeholder="https://api.example.com/get-code"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求方法</label>
|
||||
<select value={method} onChange={/* 当前回调切换 API 请求方法。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('method', event.target.value)} className="w-full ios-input rounded-xl px-3 py-3">
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">超时(秒)</label>
|
||||
<input type="number" min="1" max="60" value={timeout} onChange={/* 当前回调更新 API 请求超时秒数。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('timeout', Number(event.target.value) || 10)} className="w-full ios-input rounded-xl px-3 py-3" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-5 border-t border-blue-100 pt-5">
|
||||
<KeyValueEditor label="Headers / 请求头" value={headers} onChange={/* 当前回调保存请求头键值对象。 */ nextValue => onChange('headers', nextValue)} placeholder="Authorization" />
|
||||
{headersAction && (
|
||||
<select aria-label="请求头处理方式" value={headersAction} onChange={/* 当前回调选择请求头敏感模板处理方式。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('headersAction', event.target.value)} className="w-full ios-input rounded-xl px-3 py-2 text-sm sm:w-auto">
|
||||
<option value="retain">保留已保存请求头</option>
|
||||
<option value="replace">替换为上方字段</option>
|
||||
<option value="clear">清除已保存请求头</option>
|
||||
</select>
|
||||
)}
|
||||
|
||||
<KeyValueEditor label="Params / 查询参数" value={params} onChange={/* 当前回调保存查询参数键值对象。 */ nextValue => onChange('params', nextValue)} placeholder="order_id" />
|
||||
{paramsAction && (
|
||||
<select aria-label="查询参数处理方式" value={paramsAction} onChange={/* 当前回调选择查询参数敏感模板处理方式。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('paramsAction', event.target.value)} className="w-full ios-input rounded-xl px-3 py-2 text-sm sm:w-auto">
|
||||
<option value="retain">保留已保存查询参数</option>
|
||||
<option value="replace">替换为上方字段</option>
|
||||
<option value="clear">清除已保存查询参数</option>
|
||||
</select>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<label className="text-sm font-bold text-gray-800">Body / 请求正文</label>
|
||||
<select aria-label="请求正文 Content-Type" value={contentType} onChange={/* 当前回调切换请求正文类型。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('contentType', event.target.value)} className="ios-input rounded-xl px-3 py-2 text-sm sm:w-[290px]">
|
||||
{contentTypes.map(/* 当前回调渲染一个常用 Content-Type 选项。 */ contentTypeOption => <option key={contentTypeOption.value} value={contentTypeOption.value}>{contentTypeOption.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
{jsonBody ? (
|
||||
<textarea
|
||||
aria-label="JSON 请求正文"
|
||||
value={body}
|
||||
onChange={/* 当前回调更新 JSON 请求正文。 */ (event: ChangeEvent<HTMLTextAreaElement>) => onChange('body', event.target.value)}
|
||||
className="h-36 w-full resize-y ios-input rounded-xl px-4 py-3 font-mono text-sm"
|
||||
placeholder={'{\n "order_id": "{order_id}"\n}'}
|
||||
/>
|
||||
) : (
|
||||
<KeyValueEditor label="Body 字段" value={body} onChange={/* 当前回调保存非 JSON 正文键值对象。 */ nextValue => onChange('body', nextValue)} placeholder="field" />
|
||||
)}
|
||||
<p className="text-xs text-gray-500">GET 请求通常只使用 Params;POST 请求会按所选 Content-Type 发送 Body。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 border-t border-blue-100 pt-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">响应提取路径(可选)</label>
|
||||
<input value={responsePath} onChange={/* 当前回调更新响应提取路径。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('responsePath', event.target.value)} className="w-full ios-input rounded-xl px-4 py-3 font-mono text-sm" placeholder="data.cards[0].code" />
|
||||
</div>
|
||||
<label className="flex items-center gap-2 self-end pb-3 text-sm font-bold text-gray-700">
|
||||
<input type="checkbox" checked={retryEnabled} onChange={/* 当前回调切换 API 幂等重试。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('retryEnabled', event.target.checked)} />
|
||||
启用幂等重试(需配置 {'{idempotency_key}'})
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -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 '../../../shared/api-contract/cards';
|
||||
import type { Card } from './api';
|
||||
import { appendCardData,batchCreateCards,getCards } from './api';
|
||||
import { useCardBatchActions,useCardsData } from './hooks';
|
||||
|
||||
@@ -19,7 +19,7 @@ const batchCreateMock = vi.mocked(batchCreateCards);
|
||||
const getCardsMock = vi.mocked(getCards);
|
||||
|
||||
// cardFixture 是 data 类型卡密组的完整测试对象。
|
||||
const cardFixture: Card = { id: 1, name: '库存一', type: 'data', enabled: true, data_content: 'old', created_at: '2026-01-01', updated_at: '2026-01-01' };
|
||||
const cardFixture: Card = { id: 1, name: '库存一', type: 'data', enabled: true, data_content: 'old' };
|
||||
// loadCardsFixture 是批量操作完成后的库存刷新替身。
|
||||
const loadCardsFixture = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 Card UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface Card {
|
||||
/** 卡券组数值主键。 */
|
||||
id: number;
|
||||
/** 卡券组名称。 */
|
||||
name: string;
|
||||
/** 卡券组类型。 */
|
||||
type: 'api' | 'text' | 'data' | 'image';
|
||||
/** 卡券组说明。 */
|
||||
description?: string;
|
||||
/** 卡券组是否启用。 */
|
||||
enabled: boolean;
|
||||
// 文本类型
|
||||
text_content?: string;
|
||||
// 批量数据类型
|
||||
data_content?: string;
|
||||
// API 类型配置只保存服务端返回的脱敏摘要。
|
||||
api_config?: CardAPIConfigSummary;
|
||||
// 图片类型
|
||||
/** 图片卡券地址。 */
|
||||
image_url?: string;
|
||||
// 通用配置
|
||||
/** 卡券发送延迟秒数。 */
|
||||
delay_seconds?: number;
|
||||
// 多规格配置
|
||||
/** 是否支持多规格。 */
|
||||
is_multi_spec?: boolean;
|
||||
/** 规格名称。 */
|
||||
spec_name?: string;
|
||||
/** 规格值。 */
|
||||
spec_value?: string;
|
||||
}
|
||||
|
||||
/** API 卡券查询返回的脱敏摘要;请求头和参数永远不在此模型中。 */
|
||||
export interface CardAPIConfigSummary {
|
||||
/** API 卡券请求地址。 */
|
||||
url: string;
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求正文的 Content-Type。 */
|
||||
content_type: string;
|
||||
/** API 请求超时时间。 */
|
||||
timeout_seconds: number;
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled: boolean;
|
||||
/** 是否已配置请求头模板。 */
|
||||
headers_configured: boolean;
|
||||
/** 是否已配置请求参数模板。 */
|
||||
params_configured: boolean;
|
||||
/** 当前配置是否可以被规则使用。 */
|
||||
ready: boolean;
|
||||
/** 当前配置的非敏感校验错误。 */
|
||||
validation_error?: string;
|
||||
}
|
||||
|
||||
/** API 卡券提交用的具名配置;敏感模板为空时由服务端保留旧值。 */
|
||||
export interface CardAPIConfigInput {
|
||||
/** API 卡券请求地址。 */
|
||||
url: string;
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求超时时间。 */
|
||||
timeout_seconds: number;
|
||||
/** API 请求头 JSON 文本或对象。 */
|
||||
headers?: string | Record<string, unknown>;
|
||||
/** API 请求参数 JSON 文本或对象。 */
|
||||
params?: string | Record<string, unknown>;
|
||||
/** API 请求正文 JSON 文本或对象。 */
|
||||
body?: string | Record<string, unknown>;
|
||||
/** API 请求正文的 Content-Type。 */
|
||||
content_type?: string;
|
||||
/** 请求头的三态变更意图。 */
|
||||
headers_action?: 'retain' | 'replace' | 'clear';
|
||||
/** 请求参数的三态变更意图。 */
|
||||
params_action?: 'retain' | 'replace' | 'clear';
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled?: boolean;
|
||||
}
|
||||
|
||||
/** API 测试请求返回的非敏感诊断结果。 */
|
||||
export interface CardAPITestResult {
|
||||
/** 远端请求是否返回 2xx。 */
|
||||
status: 'success' | 'failed';
|
||||
/** 远端 HTTP 状态码。 */
|
||||
status_code: number;
|
||||
/** 远端响应媒体类型。 */
|
||||
response_content_type: string;
|
||||
/** JSON 响应顶层字段名称。 */
|
||||
response_fields: string[];
|
||||
/** 响应提取路径命中的值。 */
|
||||
extracted_value?: string;
|
||||
/** 限长响应预览。 */
|
||||
response_preview?: string;
|
||||
}
|
||||
|
||||
/** 卡券创建和更新所需的前端提交模型。 */
|
||||
export type CardMutation = Omit<Partial<Card>, 'api_config'> & {
|
||||
/** API 卡券具名请求配置或历史 JSON 字符串。 */
|
||||
api_config?: CardAPIConfigInput | string;
|
||||
};
|
||||
|
||||
/** 卡券批量创建接口的逐行结果。 */
|
||||
/** 由当前 feature adapter 归一后的 CardBatchResult UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface CardBatchResult {
|
||||
/** 表格中的原始行号。 */
|
||||
row_no: number;
|
||||
/** 当前行是否创建成功。 */
|
||||
success: boolean;
|
||||
/** 新建卡券组主键。 */
|
||||
id?: number;
|
||||
/** 卡券组名称。 */
|
||||
name: string;
|
||||
/** 卡券类型。 */
|
||||
type?: string;
|
||||
/** 当前行失败原因。 */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** 卡券批量创建接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 CardBatchResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface CardBatchResponse {
|
||||
/** 批量处理流程是否完成。 */
|
||||
success: boolean;
|
||||
/** 解析出的总行数。 */
|
||||
total: number;
|
||||
/** 创建成功行数。 */
|
||||
created: number;
|
||||
/** 创建失败行数。 */
|
||||
failed: number;
|
||||
/** 逐行处理结果。 */
|
||||
rows: CardBatchResult[];
|
||||
}
|
||||
|
||||
/** 卡券追加数据接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 CardAppendResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface CardAppendResponse {
|
||||
/** 追加操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 实际追加数量。 */
|
||||
added: number;
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { Card } from '../../../../shared/api-contract/cards';
|
||||
import type { Card } from '../api';
|
||||
|
||||
// cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。
|
||||
const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({
|
||||
@@ -11,6 +11,7 @@ const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享
|
||||
createCard: vi.fn(),
|
||||
deleteCard: vi.fn(),
|
||||
updateCard: vi.fn(),
|
||||
testCardAPI: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({
|
||||
@@ -49,6 +50,7 @@ vi.mock('../api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。
|
||||
createCard: cardListMocks.createCard,
|
||||
deleteCard: cardListMocks.deleteCard,
|
||||
updateCard: cardListMocks.updateCard,
|
||||
testCardAPI: cardListMocks.testCardAPI,
|
||||
}));
|
||||
|
||||
vi.mock('../components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({
|
||||
@@ -66,8 +68,6 @@ const cardFixture: Card = {
|
||||
description: '测试库存',
|
||||
enabled: true,
|
||||
delay_seconds: 0,
|
||||
created_at: '2026-08-15T00:00:00Z',
|
||||
updated_at: '2026-08-15T00:00:00Z',
|
||||
};
|
||||
|
||||
// textCardFixture 表示卡密页面中的文本类型卡密组。
|
||||
@@ -88,6 +88,7 @@ describe('CardList 页面组合行为', /* 当前回调验证卡密筛选、批
|
||||
cardListMocks.createCard.mockResolvedValue({ success: true, id: 3 });
|
||||
cardListMocks.deleteCard.mockResolvedValue({ success: true });
|
||||
cardListMocks.updateCard.mockResolvedValue({ success: true });
|
||||
cardListMocks.testCardAPI.mockResolvedValue({ status: 'success', status_code: 200, response_content_type: 'application/json', response_fields: ['data', 'message'], extracted_value: 'TEST-CODE' });
|
||||
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽卡密页面提示。 */ () => undefined);
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
});
|
||||
@@ -125,6 +126,33 @@ describe('CardList 页面组合行为', /* 当前回调验证卡密筛选、批
|
||||
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test('API 卡密使用三段请求编辑器并支持切换正文类型', /* 当前回调验证 API 地址、Headers、Params、Body 和 Content-Type 控件。 */ () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByText('添加新卡密'));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'API 接口' }));
|
||||
expect(screen.getByRole('heading', { name: 'API 请求配置' })).toBeTruthy();
|
||||
expect(screen.getByLabelText('Headers / 请求头第1行键名')).toBeTruthy();
|
||||
expect(screen.getByLabelText('Params / 查询参数第1行键名')).toBeTruthy();
|
||||
expect(screen.getByLabelText('JSON 请求正文')).toBeTruthy();
|
||||
fireEvent.change(screen.getByRole('combobox', { name: '请求正文 Content-Type' }), { target: { value: 'application/x-www-form-urlencoded' } });
|
||||
expect(screen.getByLabelText('Body 字段第1行键名')).toBeTruthy();
|
||||
fireEvent.click(screen.getByTitle('添加Headers / 请求头字段'));
|
||||
expect(screen.getByLabelText('Headers / 请求头第2行键名')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('新增卡密类型单行排列且 API 测试展示远端诊断', /* 当前回调验证类型顺序和 API 测试结果可见。 */ async () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByText('添加新卡密'));
|
||||
// typeButtons 保存新增弹窗中按显示顺序排列的四种卡密类型按钮。
|
||||
const typeButtons = ['批量库存', '文本', '图片', 'API 接口'].map(/* typeButtonMapper 查找当前类型按钮。 */ typeName => screen.getByRole('button', { name: typeName }));
|
||||
expect(typeButtons.map(/* typeNameMapper 读取当前类型按钮名称。 */ button => button.textContent?.trim())).toEqual(['批量库存', '文本', '图片', 'API 接口']);
|
||||
fireEvent.click(typeButtons[3]);
|
||||
fireEvent.click(screen.getByRole('button', { name: '测试请求' }));
|
||||
await waitFor(/* testResultAssertion 等待 API 测试结果展示。 */ () => expect(screen.getByText('HTTP 状态:200')).toBeTruthy());
|
||||
expect(screen.getByText('响应字段:data、message')).toBeTruthy();
|
||||
expect(screen.getByText('提取结果:TEST-CODE')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('启停、复制和删除按钮调用对应页面动作', /* 当前回调验证卡密行级动作边界。 */ async () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByRole('button', { name: '切换卡密 库存一 状态' }));
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Copy,CreditCard,Edit,FileText,Image as ImageIcon,Package,Plus,Save,Search,SlidersHorizontal,Trash2,Upload,X } from 'lucide-react';
|
||||
import { Copy,CreditCard,Edit,FileText,Globe,Image as ImageIcon,Package,Plus,Save,Search,SlidersHorizontal,Trash2,Upload,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Card } from '../api';
|
||||
import { Card, testCardAPI } from '../api';
|
||||
import { useCardActions } from '../cardActions';
|
||||
import { APIRequestBuilder } from '../components/APIRequestBuilder';
|
||||
import { BatchCardImportModal } from '../components/BatchCardImportModal';
|
||||
import { CardIcon } from '../components/CardIcon';
|
||||
import { useCardBatchActions,useCardsData } from '../hooks';
|
||||
@@ -256,71 +257,46 @@ const CardList: React.FC = () => {
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
>
|
||||
<option value="">请选择类型</option>
|
||||
<option value="data">批量库存</option>
|
||||
<option value="text">固定文字</option>
|
||||
<option value="data">批量数据</option>
|
||||
{selectedCard?.type === 'api' && <option value="api">API接口(仅保留现有配置)</option>}
|
||||
<option value="image">图片</option>
|
||||
<option value="api">API 接口</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* API 配置 */}
|
||||
{editForm.type === 'api' && (
|
||||
<div className="border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50">
|
||||
<h3 className="font-bold text-gray-900">API 配置</h3>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">API 地址</label>
|
||||
<input
|
||||
type="url"
|
||||
value={editForm.api_url || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_url: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl font-mono text-sm"
|
||||
placeholder="https://api.example.com/get-card"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求方法</label>
|
||||
<select
|
||||
value={editForm.api_method || 'GET'}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_method: e.target.value as 'GET' | 'POST' })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
>
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">超时时间(秒)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={editForm.api_timeout || 10}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_timeout: parseInt(e.target.value) || 10 })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
min="1"
|
||||
max="60"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求头(JSON 格式)</label>
|
||||
<textarea
|
||||
value={editForm.api_headers || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_headers: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
|
||||
placeholder='{"Authorization": "Bearer token"}'
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求参数(JSON 格式)</label>
|
||||
<textarea
|
||||
value={editForm.api_params || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_params: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
|
||||
placeholder='{"type": "card", "count": 1}'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<APIRequestBuilder
|
||||
url={editForm.api_url || ''}
|
||||
method={editForm.api_method || 'GET'}
|
||||
timeout={editForm.api_timeout || 10}
|
||||
headers={editForm.api_headers || ''}
|
||||
params={editForm.api_params || ''}
|
||||
contentType={editForm.api_content_type || 'application/json'}
|
||||
body={editForm.api_body || ''}
|
||||
responsePath={editForm.api_response_path || ''}
|
||||
retryEnabled={editForm.api_retry_enabled || false}
|
||||
headersAction={editForm.api_headers_action || 'retain'}
|
||||
paramsAction={editForm.api_params_action || 'retain'}
|
||||
onTest={/* editAPITest 使用当前编辑草稿发起临时 API 测试,不保存草稿。 */ () => testCardAPI({ url: editForm.api_url || '', method: editForm.api_method || 'GET', timeout_seconds: editForm.api_timeout || 10, headers: editForm.api_headers || undefined, params: editForm.api_params || undefined, content_type: editForm.api_content_type || 'application/json', body: editForm.api_body || undefined, response_path: editForm.api_response_path || undefined, retry_enabled: editForm.api_retry_enabled || false })}
|
||||
onChange={/* 当前回调把 API 请求编辑器字段写回编辑草稿。 */ (field, value) => setEditForm(/* currentUpdater 基于最新编辑草稿合并 API 字段。 */ current => ({
|
||||
...current,
|
||||
...(field === 'url' ? { api_url: String(value) } : {}),
|
||||
...(field === 'method' ? { api_method: value as 'GET' | 'POST' } : {}),
|
||||
...(field === 'timeout' ? { api_timeout: Number(value) } : {}),
|
||||
...(field === 'headers' ? { api_headers: String(value) } : {}),
|
||||
...(field === 'params' ? { api_params: String(value) } : {}),
|
||||
...(field === 'contentType' ? { api_content_type: String(value) } : {}),
|
||||
...(field === 'body' ? { api_body: String(value) } : {}),
|
||||
...(field === 'responsePath' ? { api_response_path: String(value) } : {}),
|
||||
...(field === 'retryEnabled' ? { api_retry_enabled: Boolean(value) } : {}),
|
||||
...(field === 'headersAction' ? { api_headers_action: value as 'retain' | 'replace' | 'clear' } : {}),
|
||||
...(field === 'paramsAction' ? { api_params_action: value as 'retain' | 'replace' | 'clear' } : {}),
|
||||
}))}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 固定文字配置 */}
|
||||
@@ -492,7 +468,7 @@ const CardList: React.FC = () => {
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">类型</label>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'data', content: '' })}
|
||||
@@ -517,22 +493,22 @@ const CardList: React.FC = () => {
|
||||
<ImageIcon className="w-5 h-5 mx-auto mb-1" />
|
||||
图片
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'api', content: '' })}
|
||||
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'api' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
|
||||
>
|
||||
<Globe className="w-5 h-5 mx-auto mb-1" />
|
||||
API 接口
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{addForm.type !== 'api' && <div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">
|
||||
{addForm.type === 'data' ? '库存内容(一行一个)' : addForm.type === 'text' ? '固定回复内容' : addForm.type === 'image' ? '图片 URL' : 'API 地址'}
|
||||
{addForm.type === 'data' ? '库存内容(一行一个)' : addForm.type === 'text' ? '固定回复内容' : '图片 URL'}
|
||||
</label>
|
||||
{addForm.type === 'api' ? (
|
||||
<input
|
||||
type="url"
|
||||
value={addForm.content}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
|
||||
placeholder="https://api.example.com/get-code"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
) : addForm.type === 'image' ? (
|
||||
{addForm.type === 'image' ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
type="url"
|
||||
@@ -554,34 +530,35 @@ const CardList: React.FC = () => {
|
||||
{addForm.type === 'data' && (
|
||||
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-brand">{addForm.content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim()).length}</span> 条</p>
|
||||
)}
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{addForm.type === 'api' && (
|
||||
<div className="border-t border-gray-100 pt-5 space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求方法</label>
|
||||
<select value={addForm.api_method} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_method: e.target.value as 'GET' | 'POST'})} className="w-full ios-input px-4 py-3 rounded-xl">
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">超时时间(秒)</label>
|
||||
<input type="number" min="1" max="60" value={addForm.api_timeout} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_timeout: parseInt(e.target.value) || 10})} className="w-full ios-input px-4 py-3 rounded-xl" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求头(JSON)</label>
|
||||
<textarea value={addForm.api_headers} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_headers: e.target.value})} className="w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs" placeholder='{"Authorization":"Bearer token"}' />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求参数(JSON)</label>
|
||||
<textarea value={addForm.api_params} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_params: e.target.value})} className="w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs" placeholder='{"order_id":"{order_id}"}' />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<APIRequestBuilder
|
||||
url={addForm.content}
|
||||
method={addForm.api_method}
|
||||
timeout={addForm.api_timeout}
|
||||
headers={addForm.api_headers}
|
||||
params={addForm.api_params}
|
||||
contentType={addForm.api_content_type}
|
||||
body={addForm.api_body}
|
||||
responsePath={addForm.api_response_path}
|
||||
retryEnabled={addForm.api_retry_enabled}
|
||||
onTest={/* addAPITest 使用当前新增草稿发起临时 API 测试,不创建卡密。 */ () => testCardAPI({ url: addForm.content, method: addForm.api_method, timeout_seconds: addForm.api_timeout, headers: addForm.api_headers || undefined, params: addForm.api_params || undefined, content_type: addForm.api_content_type, body: addForm.api_body || undefined, response_path: addForm.api_response_path || undefined, retry_enabled: addForm.api_retry_enabled })}
|
||||
onChange={/* 当前回调把 API 请求编辑器字段写回新增草稿。 */ (field, value) => setAddForm(/* currentUpdater 基于最新新增草稿合并 API 字段。 */ current => ({
|
||||
...current,
|
||||
...(field === 'url' ? { content: String(value) } : {}),
|
||||
...(field === 'method' ? { api_method: value as 'GET' | 'POST' } : {}),
|
||||
...(field === 'timeout' ? { api_timeout: Number(value) } : {}),
|
||||
...(field === 'headers' ? { api_headers: String(value) } : {}),
|
||||
...(field === 'params' ? { api_params: String(value) } : {}),
|
||||
...(field === 'contentType' ? { api_content_type: String(value) } : {}),
|
||||
...(field === 'body' ? { api_body: String(value) } : {}),
|
||||
...(field === 'responsePath' ? { api_response_path: String(value) } : {}),
|
||||
...(field === 'retryEnabled' ? { api_retry_enabled: Boolean(value) } : {}),
|
||||
}))}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4">
|
||||
|
||||
@@ -23,6 +23,14 @@ export interface AddCardForm {
|
||||
api_headers: string;
|
||||
// api_params 是 API 请求参数 JSON 文本。
|
||||
api_params: string;
|
||||
// api_content_type 是 API 请求正文的 Content-Type。
|
||||
api_content_type: string;
|
||||
// api_body 是 API 请求正文 JSON 文本或键值对象 JSON 文本。
|
||||
api_body: string;
|
||||
// api_response_path 是 API 响应提取路径。
|
||||
api_response_path: string;
|
||||
// api_retry_enabled 表示是否启用带幂等键的重试。
|
||||
api_retry_enabled: boolean;
|
||||
}
|
||||
|
||||
// EditCardForm 描述编辑卡密组时的表单字段和 API 扩展字段。
|
||||
@@ -37,6 +45,18 @@ export type EditCardForm = Partial<Card> & {
|
||||
api_headers?: string;
|
||||
// api_params 是编辑中的 API 请求参数 JSON 文本。
|
||||
api_params?: string;
|
||||
// api_content_type 是编辑中的 API 请求正文 Content-Type。
|
||||
api_content_type?: string;
|
||||
// api_body 是编辑中的 API 请求正文 JSON 文本或键值对象 JSON 文本。
|
||||
api_body?: string;
|
||||
// api_response_path 是编辑中的 API 响应提取路径。
|
||||
api_response_path?: string;
|
||||
// api_retry_enabled 表示编辑中是否启用带幂等键的重试。
|
||||
api_retry_enabled?: boolean;
|
||||
// api_headers_action 保存请求头模板的三态变更意图。
|
||||
api_headers_action?: 'retain' | 'replace' | 'clear';
|
||||
// api_params_action 保存请求参数模板的三态变更意图。
|
||||
api_params_action?: 'retain' | 'replace' | 'clear';
|
||||
};
|
||||
|
||||
// CardBatchTab 表示批量导入弹窗当前展示的操作页签。
|
||||
|
||||
@@ -1,29 +1,52 @@
|
||||
import {
|
||||
AccountDetail,
|
||||
ChatBuyerNote,
|
||||
ChatMessage,
|
||||
ChatQuickReply,
|
||||
ChatSession,
|
||||
OperationResponse
|
||||
} from '../../../shared/api-contract/chat';
|
||||
import { get,post,postForm,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/chat';
|
||||
} from './models';
|
||||
import { contractClient, contractMultipartBody, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
export type * from './models';
|
||||
import type { ChatReadReceipt } from './types';
|
||||
|
||||
/** 聊天账号选择器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => {
|
||||
// response 是账号摘要 transport DTO 集合,转换后只向聊天 UI 暴露非敏感字段。
|
||||
const response = await runContractRequest(/* signal 是本次聊天账号摘要请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options);
|
||||
return response.map(/* item 是当前待转换的账号摘要 DTO。 */ item => ({
|
||||
id: item.id,
|
||||
enabled: item.enabled,
|
||||
auto_confirm: item.auto_confirm,
|
||||
remark: item.remark,
|
||||
pause_duration: item.pause_duration,
|
||||
paused_until: item.paused_until,
|
||||
paused: item.paused,
|
||||
username: item.username,
|
||||
show_browser: item.show_browser,
|
||||
nickname: item.nickname,
|
||||
avatar_url: item.avatar_url,
|
||||
profile_error: item.profile_error,
|
||||
}));
|
||||
};
|
||||
|
||||
/** 聊天运行提示读取账号连接状态索引。 */
|
||||
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 const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise<Record<string, { /** 当前连接状态。 */ state: NonNullable<AccountDetail['runtime_state']>; /** 状态说明。 */ message?: string; /** 是否已连接。 */ connected: boolean; /** 连续失败次数。 */ failures: number; /** 最近更新时间。 */ updated_at: string }>> =>
|
||||
runContractRequest(/* signal 是本次聊天运行状态请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/runtime-status', { signal }), 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 };
|
||||
const response = await runContractRequest(
|
||||
/* signal 是本次聊天会话分页请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/chat/sessions', {
|
||||
params: { query: { account_id: accountId, cursor, refresh: refresh ? 1 : undefined } },
|
||||
signal,
|
||||
}),
|
||||
{ timeoutMs: refresh ? 60_000 : options?.timeoutMs, signal: options?.signal },
|
||||
);
|
||||
return response;
|
||||
};
|
||||
|
||||
// getChatSessions 读取聊天会话列表。
|
||||
@@ -40,35 +63,108 @@ export interface ChatMessagePage {
|
||||
// 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 };
|
||||
const response = await runContractRequest(/* signal 是本次聊天消息分页请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/chat/messages', {
|
||||
params: { query: { account_id: accountId, chat_id: chatId, cursor, before_id: beforeId } },
|
||||
signal,
|
||||
}), options);
|
||||
return response;
|
||||
};
|
||||
|
||||
// getChatMessages 读取聊天消息列表。
|
||||
export const getChatMessages = async (accountId: string, chatId: string, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessage[]> =>
|
||||
(await getChatMessagePage(accountId, chatId, undefined, beforeId, options)).messages;
|
||||
|
||||
/** 查询当前账号可复用的人工快捷回复。 */
|
||||
export const getChatQuickReplies = async (accountId: string, options?: RequestControlOptions): Promise<ChatQuickReply[]> => {
|
||||
// response 保存契约客户端返回的快捷回复列表 DTO,随后转换为 feature UI 模型。
|
||||
const response = await runContractRequest(/* signal 是本次账号快捷回复查询的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/chat/quick-replies', {
|
||||
params: { query: { account_id: accountId } },
|
||||
signal,
|
||||
}), options);
|
||||
return response.quick_replies.map(/* reply 是当前待转换的快捷回复 DTO。 */ reply => ({
|
||||
id: reply.id,
|
||||
account_id: reply.account_id,
|
||||
content: reply.content,
|
||||
created_at: reply.created_at,
|
||||
}));
|
||||
};
|
||||
|
||||
/** 为当前账号新增人工快捷回复。 */
|
||||
export const createChatQuickReply = async (accountId: string, content: string, options?: RequestControlOptions): Promise<ChatQuickReply> => {
|
||||
// response 保存创建接口返回的快捷回复 DTO,转换后不向组件暴露生成类型。
|
||||
const response = await runContractRequest(/* signal 是本次新增快捷回复请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/chat/quick-replies', {
|
||||
body: { account_id: accountId, content },
|
||||
signal,
|
||||
}), options);
|
||||
return { id: response.id, account_id: response.account_id, content: response.content, created_at: response.created_at };
|
||||
};
|
||||
|
||||
/** 删除当前账号下指定的人工快捷回复。 */
|
||||
export const deleteChatQuickReply = async (accountId: string, quickReplyId: number, options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
runContractRequest(/* signal 是本次删除快捷回复请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/chat/quick-replies/{quick_reply_id}', {
|
||||
params: { path: { quick_reply_id: quickReplyId }, query: { account_id: accountId } },
|
||||
signal,
|
||||
}), options);
|
||||
|
||||
/** 查询当前账号下指定买家的完整备注;未填写时仍返回空内容。 */
|
||||
export const getChatBuyerNote = async (accountId: string, buyerId: string, options?: RequestControlOptions): Promise<ChatBuyerNote> => {
|
||||
// response 保存契约客户端返回的买家备注 DTO,转换后由聊天 feature 管理。
|
||||
const response = await runContractRequest(/* signal 是本次买家备注查询的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/chat/buyer-notes/{buyer_id}', {
|
||||
params: { path: { buyer_id: buyerId }, query: { account_id: accountId } },
|
||||
signal,
|
||||
}), options);
|
||||
return { account_id: response.account_id, buyer_id: response.buyer_id, content: response.content, updated_at: response.updated_at };
|
||||
};
|
||||
|
||||
/** 保存当前账号下指定买家的完整备注;空内容会清除已有备注。 */
|
||||
export const saveChatBuyerNote = async (accountId: string, buyerId: string, content: string, options?: RequestControlOptions): Promise<ChatBuyerNote> => {
|
||||
// response 保存保存接口返回的最终买家备注 DTO。
|
||||
const response = await runContractRequest(/* signal 是本次买家备注保存请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/chat/buyer-notes/{buyer_id}', {
|
||||
params: { path: { buyer_id: buyerId } },
|
||||
body: { account_id: accountId, content },
|
||||
signal,
|
||||
}), options);
|
||||
return { account_id: response.account_id, buyer_id: response.buyer_id, content: response.content, updated_at: response.updated_at };
|
||||
};
|
||||
|
||||
// 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);
|
||||
}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> =>
|
||||
runContractRequest(/* signal 是本次聊天文本发送请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/chat/messages', { body: input, signal }), 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 处理流程。
|
||||
// form 保存聊天图片的原生 multipart 请求体,浏览器负责生成正确的 boundary。
|
||||
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 });
|
||||
form.set('account_id', input.account_id);
|
||||
form.set('chat_id', input.chat_id);
|
||||
form.set('buyer_id', input.buyer_id);
|
||||
form.set('image', input.image);
|
||||
// optionalFields 保存可空展示字段;仅提交非空值,防止 FormData 将 undefined 字符串化后污染聊天元数据。
|
||||
const optionalFields = [
|
||||
['buyer_name', input.buyer_name],
|
||||
['buyer_avatar_url', input.buyer_avatar_url],
|
||||
['item_id', input.item_id],
|
||||
['item_title', input.item_title],
|
||||
] as const;
|
||||
for (const /* fieldName 和 fieldValue 分别表示可选表单字段名称及其当前用户可见元数据。 */ [fieldName, fieldValue] of optionalFields) {
|
||||
if (fieldValue) form.set(fieldName, fieldValue);
|
||||
}
|
||||
return runContractRequest(/* signal 是本次聊天图片发送请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/chat/images', {
|
||||
// body 保持原生 FormData;共享契约层仅提供运行时类型适配,不定义业务传输 DTO。
|
||||
body: contractMultipartBody(form),
|
||||
signal,
|
||||
}), { timeoutMs: 120_000, ...options });
|
||||
};
|
||||
|
||||
/** 向平台确认指定会话中的入站消息已读。 */
|
||||
export const markChatRead = async (accountId: string, chatId: string, messageIDs: ChatReadReceipt[], options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId, message_ids: messageIDs }, options);
|
||||
runContractRequest(/* signal 是本次聊天已读上报请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/chat/read', {
|
||||
body: { account_id: accountId, chat_id: chatId, message_ids: messageIDs.map(/* receipt 是当前待序列化的平台已读回执。 */ receipt => ({ messageId: receipt.messageId, sessionId: receipt.sessionId, cid: receipt.cid, conversationType: receipt.conversationType })) },
|
||||
signal,
|
||||
}), options);
|
||||
@@ -0,0 +1,154 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
import { AudioMessage, formatAudioTime, secureAudioURL } from './AudioMessage';
|
||||
|
||||
/** recorderHarness 保存可观察的解码器状态和事件回调,使测试不依赖浏览器 AudioContext。 */
|
||||
const recorderHarness = vi.hoisted(() => ({
|
||||
/** initialized 表示测试解码器是否已完成 AMR 初始化。 */
|
||||
initialized: false,
|
||||
/** playing 表示测试解码器当前是否播放。 */
|
||||
playing: false,
|
||||
/** paused 表示测试解码器当前是否暂停。 */
|
||||
paused: false,
|
||||
/** initError 控制下一次媒体初始化是否失败。 */
|
||||
initError: null as Error | null,
|
||||
/** playEvent、pauseEvent、resumeEvent、stopEvent 和 endedEvent 保存组件注册的生命周期回调。 */
|
||||
playEvent: null as (() => void) | null,
|
||||
pauseEvent: null as (() => void) | null,
|
||||
resumeEvent: null as (() => void) | null,
|
||||
stopEvent: null as (() => void) | null,
|
||||
endedEvent: null as (() => void) | null,
|
||||
/** initWithUrl 记录待解码媒体地址,并按 initError 决定成功或失败。 */
|
||||
initWithUrl: vi.fn(async function initWithUrl(): Promise<void> {
|
||||
if (recorderHarness.initError) throw recorderHarness.initError;
|
||||
recorderHarness.initialized = true;
|
||||
}),
|
||||
/** play 从头播放并触发组件注册的播放事件。 */
|
||||
play: vi.fn(function play(): void {
|
||||
recorderHarness.playing = true;
|
||||
recorderHarness.paused = false;
|
||||
recorderHarness.playEvent?.();
|
||||
}),
|
||||
/** pause 暂停播放并触发组件注册的暂停事件。 */
|
||||
pause: vi.fn(function pause(): void {
|
||||
recorderHarness.playing = false;
|
||||
recorderHarness.paused = true;
|
||||
recorderHarness.pauseEvent?.();
|
||||
}),
|
||||
/** resume 从暂停位置继续并触发组件注册的恢复事件。 */
|
||||
resume: vi.fn(function resume(): void {
|
||||
recorderHarness.playing = true;
|
||||
recorderHarness.paused = false;
|
||||
recorderHarness.resumeEvent?.();
|
||||
}),
|
||||
/** destroy 记录组件是否释放解码缓存和浏览器音频节点。 */
|
||||
destroy: vi.fn(),
|
||||
/** isInit 返回测试解码器是否已经完成初始化。 */
|
||||
isInit: vi.fn(/* 当前回调返回测试解码器的初始化状态。 */ (): boolean => recorderHarness.initialized),
|
||||
/** isPlaying 返回测试解码器当前播放状态。 */
|
||||
isPlaying: vi.fn(/* 当前回调返回测试解码器的播放状态。 */ (): boolean => recorderHarness.playing),
|
||||
/** isPaused 返回测试解码器当前暂停状态。 */
|
||||
isPaused: vi.fn(/* 当前回调返回测试解码器的暂停状态。 */ (): boolean => recorderHarness.paused),
|
||||
/** getDuration 返回三秒的确定性语音长度。 */
|
||||
getDuration: vi.fn(/* 当前回调提供确定性的三秒总时长。 */ (): number => 3),
|
||||
/** getCurrentPosition 返回一秒的确定性播放进度。 */
|
||||
getCurrentPosition: vi.fn(/* 当前回调提供确定性的一秒播放进度。 */ (): number => 1),
|
||||
/** onPlay、onPause、onResume、onStop 和 onEnded 接收组件注册的解码器事件。 */
|
||||
onPlay: vi.fn(/* callback 是组件注册的播放开始回调。 */ (callback: () => void): void => { recorderHarness.playEvent = callback; }),
|
||||
onPause: vi.fn(/* callback 是组件注册的播放暂停回调。 */ (callback: () => void): void => { recorderHarness.pauseEvent = callback; }),
|
||||
onResume: vi.fn(/* callback 是组件注册的播放恢复回调。 */ (callback: () => void): void => { recorderHarness.resumeEvent = callback; }),
|
||||
onStop: vi.fn(/* callback 是组件注册的主动停止回调。 */ (callback: () => void): void => { recorderHarness.stopEvent = callback; }),
|
||||
onEnded: vi.fn(/* callback 是组件注册的自然结束回调。 */ (callback: () => void): void => { recorderHarness.endedEvent = callback; }),
|
||||
}));
|
||||
|
||||
vi.mock('benz-amr-recorder', /* 当前工厂回调用确定性替身隔离浏览器音频实现。 */ () => ({
|
||||
/** default 模拟聊天路由加载后通过 new 创建的 AMR 解码器。 */
|
||||
default: vi.fn(/* MockBenzAMRRecorder 返回当前测试共享的解码器替身。 */ function MockBenzAMRRecorder() { return recorderHarness; }),
|
||||
}));
|
||||
|
||||
/** resetRecorderHarness 清除测试间的播放状态、回调和调用记录。 */
|
||||
function resetRecorderHarness(): void {
|
||||
recorderHarness.initialized = false;
|
||||
recorderHarness.playing = false;
|
||||
recorderHarness.paused = false;
|
||||
recorderHarness.initError = null;
|
||||
recorderHarness.playEvent = null;
|
||||
recorderHarness.pauseEvent = null;
|
||||
recorderHarness.resumeEvent = null;
|
||||
recorderHarness.stopEvent = null;
|
||||
recorderHarness.endedEvent = null;
|
||||
// method 保存当前待清理调用记录的测试替身。
|
||||
for (const /* method 是当前待清理调用记录的测试替身。 */ method of [
|
||||
recorderHarness.initWithUrl, recorderHarness.play, recorderHarness.pause, recorderHarness.resume,
|
||||
recorderHarness.destroy, recorderHarness.isInit, recorderHarness.isPlaying, recorderHarness.isPaused,
|
||||
recorderHarness.getDuration, recorderHarness.getCurrentPosition, recorderHarness.onPlay,
|
||||
recorderHarness.onPause, recorderHarness.onResume, recorderHarness.onStop, recorderHarness.onEnded,
|
||||
]) method.mockClear();
|
||||
}
|
||||
|
||||
beforeEach(/* 当前回调在每条测试前恢复解码器初始状态。 */ () => resetRecorderHarness());
|
||||
afterEach(/* 当前回调清理 React 容器及临时全局对象。 */ () => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('AudioMessage', /* 当前测试套件覆盖语音组件的主要交互生命周期。 */ () => {
|
||||
test('首次点击延迟解码并支持播放、暂停和继续', /* 当前测试回调验证成功播放路径和资源释放。 */ async () => {
|
||||
// view 保存组件渲染句柄,用于验证卸载会释放解码器。
|
||||
const view = render(<AudioMessage messageKey="voice-1" src="https://cdn.example/voice.amr" outgoing={false} initialDuration={3} />);
|
||||
expect(screen.getByText('0:03')).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole('button', { name: '播放语音消息' }));
|
||||
await waitFor(/* 当前轮询回调等待异步解码完成并进入播放态。 */ () => expect(screen.getByRole('button', { name: '暂停语音消息' })).toBeTruthy());
|
||||
expect(recorderHarness.initWithUrl).toHaveBeenCalledWith('https://cdn.example/voice.amr');
|
||||
expect(screen.getByText('0:00 / 0:03')).toBeTruthy();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '暂停语音消息' }));
|
||||
expect(screen.getByRole('button', { name: '继续播放语音消息' })).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole('button', { name: '继续播放语音消息' }));
|
||||
expect(recorderHarness.resume).toHaveBeenCalledTimes(1);
|
||||
view.unmount();
|
||||
expect(recorderHarness.destroy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('解码失败后展示可重试状态', /* 当前测试回调验证失败提示与再次初始化。 */ async () => {
|
||||
recorderHarness.initError = new Error('decode failed');
|
||||
render(<AudioMessage messageKey="voice-error" src="https://cdn.example/broken.amr" outgoing initialDuration={3} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: '播放语音消息' }));
|
||||
await waitFor(/* 当前轮询回调等待失败状态写入界面。 */ () => expect(screen.getByRole('button', { name: '重新加载语音消息' })).toBeTruthy());
|
||||
expect(screen.getByText('加载失败,点击重试')).toBeTruthy();
|
||||
|
||||
recorderHarness.initError = null;
|
||||
fireEvent.click(screen.getByRole('button', { name: '重新加载语音消息' }));
|
||||
await waitFor(/* 当前轮询回调等待重试成功并开始播放。 */ () => expect(screen.getByRole('button', { name: '暂停语音消息' })).toBeTruthy());
|
||||
expect(recorderHarness.initWithUrl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test('另一条语音开始时暂停当前播放器', /* 当前测试回调验证同页语音互斥播放。 */ async () => {
|
||||
render(<>
|
||||
<AudioMessage messageKey="voice-a" src="https://cdn.example/a.amr" outgoing={false} />
|
||||
<AudioMessage messageKey="voice-b" src="https://cdn.example/b.amr" outgoing={false} />
|
||||
</>);
|
||||
// playButtons 按 DOM 顺序保存两条语音的初始播放按钮。
|
||||
const playButtons = screen.getAllByRole('button', { name: '播放语音消息' });
|
||||
fireEvent.click(playButtons[0]);
|
||||
await waitFor(/* 当前轮询回调等待首条语音进入播放态。 */ () => expect(recorderHarness.play).toHaveBeenCalledTimes(1));
|
||||
act(/* 当前回调模拟另一条语音取得播放权。 */ () => window.dispatchEvent(new CustomEvent('ydisks:chat-audio-play', { detail: 'voice-b' })));
|
||||
expect(recorderHarness.pause).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('audio helpers', /* 当前测试套件覆盖媒体地址和时长格式化边界。 */ () => {
|
||||
test('只在 HTTPS 页面升级阿里云 OSS 的语音协议', /* 当前测试回调验证混合内容兼容范围。 */ () => {
|
||||
vi.stubGlobal('location', { protocol: 'https:' });
|
||||
expect(secureAudioURL('http://voice.oss-cn-hangzhou.aliyuncs.com/a.amr?token=1')).toBe('https://voice.oss-cn-hangzhou.aliyuncs.com/a.amr?token=1');
|
||||
expect(secureAudioURL('http://example.com/a.amr')).toBe('http://example.com/a.amr');
|
||||
});
|
||||
|
||||
test('把播放器秒数格式化为固定宽度时间', /* 当前测试回调验证正常、跨分钟和非法秒数。 */ () => {
|
||||
expect(formatAudioTime(3.8)).toBe('0:03');
|
||||
expect(formatAudioTime(65)).toBe('1:05');
|
||||
expect(formatAudioTime(Number.NaN)).toBe('0:00');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,240 @@
|
||||
import { Loader2, Pause, Play, RotateCcw } from 'lucide-react';
|
||||
import React from 'react';
|
||||
|
||||
import BenzAMRRecorder from 'benz-amr-recorder';
|
||||
|
||||
/** AudioMessageProps 描述一条已归一化闲鱼语音消息的播放输入。 */
|
||||
interface AudioMessageProps {
|
||||
/** messageKey 是消息稳定键,用于在多条语音之间协调互斥播放。 */
|
||||
messageKey: string;
|
||||
/** src 是平台返回的 AMR 媒体地址,不包含账号 Cookie 等登录凭证。 */
|
||||
src: string;
|
||||
/** outgoing 控制语音气泡使用本人或对方的视觉方向。 */
|
||||
outgoing: boolean;
|
||||
/** initialDuration 是平台载荷提供的秒级时长,首次点击前用于直接展示语音长度。 */
|
||||
initialDuration?: number;
|
||||
}
|
||||
|
||||
/** AudioPlaybackState 描述语音从未加载、异步解码到播放结束的短暂 UI 状态。 */
|
||||
type AudioPlaybackState = 'idle' | 'loading' | 'playing' | 'paused' | 'error';
|
||||
|
||||
/** audioPlaybackEventName 是同页语音播放器之间广播互斥播放请求的事件名称。 */
|
||||
const audioPlaybackEventName = 'ydisks:chat-audio-play';
|
||||
|
||||
/** waveformBars 保存紧凑语音波形的相对高度,避免用随机布局造成每次渲染跳动。 */
|
||||
const waveformBars = [6, 10, 15, 8, 17, 12, 7, 16, 11, 6, 14, 9];
|
||||
|
||||
/**
|
||||
* secureAudioURL 在 HTTPS 页面中只升级阿里云 OSS 的 HTTP 媒体地址,避免混合内容拦截。
|
||||
* source 是平台返回的原始媒体地址;返回值保持查询参数不变,无法解析时原样返回。
|
||||
*/
|
||||
export function secureAudioURL(source: string): string {
|
||||
// trimmedURL 去除协议载荷外围空白,防止合法 URL 因格式噪声加载失败。
|
||||
const trimmedURL = source.trim();
|
||||
if (typeof location === 'undefined' || location.protocol !== 'https:') return trimmedURL;
|
||||
try {
|
||||
// mediaURL 用标准 URL 解析器保留签名查询参数,仅允许改写已验证支持 TLS 的 OSS 域名。
|
||||
const mediaURL = new URL(trimmedURL);
|
||||
if (mediaURL.protocol === 'http:' && mediaURL.hostname.endsWith('.aliyuncs.com')) {
|
||||
mediaURL.protocol = 'https:';
|
||||
}
|
||||
return mediaURL.toString();
|
||||
} catch (parseError /* parseError 仅说明平台媒体地址不是有效绝对 URL,不向界面暴露其内容。 */) {
|
||||
return trimmedURL;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* formatAudioTime 把播放器提供的秒数格式化为 mm:ss。
|
||||
* seconds 是当前进度或总时长;非有限值按零处理,返回固定宽度时间文本。
|
||||
*/
|
||||
export function formatAudioTime(seconds: number): string {
|
||||
// safeSeconds 是已取整且不小于零的可展示秒数。
|
||||
const safeSeconds = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0;
|
||||
// minutes 是完整分钟部分。
|
||||
const minutes = Math.floor(safeSeconds / 60);
|
||||
// remainderSeconds 是不足一分钟的秒数部分。
|
||||
const remainderSeconds = safeSeconds % 60;
|
||||
return `${minutes}:${remainderSeconds.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** announceAudioPlayback 通知同一聊天页的其他语音暂停,messageKey 标识新取得播放权的消息。 */
|
||||
function announceAudioPlayback(messageKey: string): void {
|
||||
window.dispatchEvent(new CustomEvent<string>(audioPlaybackEventName, { detail: messageKey }));
|
||||
}
|
||||
|
||||
/** AudioMessage 提供 AMR 延迟解码、播放/暂停、进度反馈、失败重试及组件卸载清理。 */
|
||||
export const AudioMessage: React.FC<AudioMessageProps> = ({ messageKey, src, outgoing, initialDuration = 0 }) => {
|
||||
/** playerRef 拥有当前消息的 AMR 解码器;组件卸载或地址变化时负责 destroy。 */
|
||||
const playerRef = React.useRef<BenzAMRRecorder | null>(null);
|
||||
/** generationRef 标识最近一次异步初始化,晚到的媒体下载或解码结果不得覆盖新消息状态。 */
|
||||
const generationRef = React.useRef(0);
|
||||
/** playbackState 和 setPlaybackState 保存仅供当前气泡展示的播放生命周期状态。 */
|
||||
const [playbackState, setPlaybackState] = React.useState<AudioPlaybackState>('idle');
|
||||
/** duration 和 setDuration 保存平台载荷或解码器确认的总时长,单位为秒,不属于服务端消息状态。 */
|
||||
const [duration, setDuration] = React.useState(initialDuration);
|
||||
/** progress 和 setProgress 保存播放进度,单位为秒,由播放期间的短定时器更新。 */
|
||||
const [progress, setProgress] = React.useState(0);
|
||||
|
||||
/**
|
||||
* 地址变化或组件卸载时销毁解码器并使未完成初始化失效;底层 XHR 无取消接口,代次检查负责隔离晚到结果。
|
||||
*/
|
||||
React.useEffect(/* 当前回调登记媒体地址对应的解码器释放责任。 */ () => {
|
||||
return /* 当前清理回调在地址变化或组件卸载时销毁当前解码器。 */ () => {
|
||||
generationRef.current += 1;
|
||||
playerRef.current?.destroy();
|
||||
playerRef.current = null;
|
||||
};
|
||||
}, [src]);
|
||||
|
||||
/** 服务端刷新同一条语音的时长时同步初始展示值,播放后的解码结果仍可覆盖该值。 */
|
||||
React.useEffect(/* 当前回调同步服务端提供的秒级语音时长。 */ () => {
|
||||
setDuration(Math.max(0, initialDuration));
|
||||
}, [initialDuration]);
|
||||
|
||||
/** 监听同页其他语音取得播放权的事件,并在清理阶段移除全局监听器。 */
|
||||
React.useEffect(/* 当前回调同步同页语音播放器的互斥事件监听。 */ () => {
|
||||
/** pauseForOtherMessage 在另一条消息开始播放时暂停当前解码器,避免多个声音重叠。 */
|
||||
const pauseForOtherMessage = (event: Event): void => {
|
||||
// activeMessageKey 是新取得播放权的消息键;类型转换仅发生在本模块自定义事件边界。
|
||||
const activeMessageKey = (event as CustomEvent<string>).detail;
|
||||
// player 是当前组件拥有的解码器;未初始化或已暂停时无需动作。
|
||||
const player = playerRef.current;
|
||||
if (activeMessageKey !== messageKey && player?.isPlaying()) player.pause();
|
||||
};
|
||||
window.addEventListener(audioPlaybackEventName, pauseForOtherMessage);
|
||||
return /* 当前清理回调移除播放器互斥事件监听。 */ () => window.removeEventListener(audioPlaybackEventName, pauseForOtherMessage);
|
||||
}, [messageKey]);
|
||||
|
||||
/** 播放期间轮询解码器进度;暂停、结束或卸载时立即清理定时器。 */
|
||||
React.useEffect(/* 当前回调只在播放态创建进度轮询定时器。 */ () => {
|
||||
if (playbackState !== 'playing') return undefined;
|
||||
// progressTimer 每 100 毫秒同步一次可见进度,不参与音频时序控制。
|
||||
const progressTimer = window.setInterval(/* 当前定时回调从解码器读取最新播放位置。 */ () => {
|
||||
// player 是本次轮询读取的当前解码器,销毁后不再更新 UI。
|
||||
const player = playerRef.current;
|
||||
if (player) setProgress(player.getCurrentPosition());
|
||||
}, 100);
|
||||
return /* 当前清理回调在播放态结束时释放进度定时器。 */ () => window.clearInterval(progressTimer);
|
||||
}, [playbackState]);
|
||||
|
||||
/** bindPlayerEvents 把解码器事件映射为当前代次的 React 状态,避免陈旧实例回写。 */
|
||||
const bindPlayerEvents = (player: BenzAMRRecorder, generation: number): void => {
|
||||
/** isCurrentGeneration 判断回调所属解码器是否仍由当前气泡持有。 */
|
||||
const isCurrentGeneration = (): boolean => generationRef.current === generation && playerRef.current === player;
|
||||
player.onPlay(/* 当前回调在音频从头开始时切换播放态。 */ () => {
|
||||
if (isCurrentGeneration()) setPlaybackState('playing');
|
||||
});
|
||||
player.onResume(/* 当前回调在暂停后继续时恢复播放态。 */ () => {
|
||||
if (isCurrentGeneration()) setPlaybackState('playing');
|
||||
});
|
||||
player.onPause(/* 当前回调在用户或互斥规则暂停时保留当前进度。 */ () => {
|
||||
if (isCurrentGeneration()) setPlaybackState('paused');
|
||||
});
|
||||
player.onStop(/* 当前回调在主动停止时复位到语音开头。 */ () => {
|
||||
if (!isCurrentGeneration()) return;
|
||||
setPlaybackState('idle');
|
||||
setProgress(0);
|
||||
});
|
||||
player.onEnded(/* 当前回调在自然播放结束时恢复可重新播放状态。 */ () => {
|
||||
if (!isCurrentGeneration()) return;
|
||||
setPlaybackState('idle');
|
||||
setProgress(0);
|
||||
});
|
||||
};
|
||||
|
||||
/** handleToggle 响应播放按钮:已播放时暂停,已暂停时继续,首次点击才下载并解码 AMR 数据。 */
|
||||
const handleToggle = async (): Promise<void> => {
|
||||
// currentPlayer 是按钮点击时已经存在的解码器实例。
|
||||
const currentPlayer = playerRef.current;
|
||||
if (currentPlayer?.isPlaying()) {
|
||||
currentPlayer.pause();
|
||||
return;
|
||||
}
|
||||
if (currentPlayer?.isPaused()) {
|
||||
announceAudioPlayback(messageKey);
|
||||
currentPlayer.resume();
|
||||
return;
|
||||
}
|
||||
if (currentPlayer?.isInit()) {
|
||||
announceAudioPlayback(messageKey);
|
||||
currentPlayer.play();
|
||||
return;
|
||||
}
|
||||
if (playbackState === 'loading') return;
|
||||
|
||||
// generation 是本次动态导入和网络解码的代次,地址切换或卸载会令其失效。
|
||||
const generation = generationRef.current + 1;
|
||||
generationRef.current = generation;
|
||||
setPlaybackState('loading');
|
||||
setProgress(0);
|
||||
try {
|
||||
// player 拥有这条消息的解码缓存;解码器随聊天路由加载,媒体数据仍只在首次点击时下载。
|
||||
const player = new BenzAMRRecorder();
|
||||
playerRef.current = player;
|
||||
bindPlayerEvents(player, generation);
|
||||
await player.initWithUrl(secureAudioURL(src));
|
||||
if (generationRef.current !== generation || playerRef.current !== player) {
|
||||
player.destroy();
|
||||
return;
|
||||
}
|
||||
setDuration(player.getDuration() || Math.max(0, initialDuration));
|
||||
announceAudioPlayback(messageKey);
|
||||
player.play();
|
||||
} catch (loadError /* loadError 可能来自跨域下载或 AMR 解码,界面仅显示可重试提示。 */) {
|
||||
if (generationRef.current !== generation) return;
|
||||
playerRef.current?.destroy();
|
||||
playerRef.current = null;
|
||||
setPlaybackState('error');
|
||||
setProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// visibleSeconds 在播放或暂停时显示当前进度,其余状态显示平台或解码器提供的总时长。
|
||||
const visibleSeconds = playbackState === 'playing' || playbackState === 'paused' ? progress : duration;
|
||||
// timeLabel 在静止状态突出总时长,播放时再补充当前进度,避免占用单行语音气泡的垂直空间。
|
||||
const timeLabel = duration > 0 ? (playbackState === 'playing' || playbackState === 'paused' ? `${formatAudioTime(visibleSeconds)} / ${formatAudioTime(duration)}` : formatAudioTime(duration)) : '--:--';
|
||||
// statusLabel 为播放器状态提供不依赖图标和颜色的可读说明。
|
||||
const statusLabel = playbackState === 'loading' ? '正在解码'
|
||||
: playbackState === 'playing' ? '正在播放'
|
||||
: playbackState === 'paused' ? '已暂停'
|
||||
: playbackState === 'error' ? '加载失败,点击重试'
|
||||
: '语音消息';
|
||||
// buttonLabel 为播放按钮提供完整的辅助技术操作名称。
|
||||
const buttonLabel = playbackState === 'playing' ? '暂停语音消息'
|
||||
: playbackState === 'paused' ? '继续播放语音消息'
|
||||
: playbackState === 'error' ? '重新加载语音消息'
|
||||
: playbackState === 'loading' ? '正在加载语音消息'
|
||||
: '播放语音消息';
|
||||
|
||||
return (
|
||||
<div className={`flex h-11 min-w-56 items-center gap-2 rounded-2xl border px-2 shadow-sm ${outgoing ? 'rounded-br-md border-sky-400 bg-sky-500 text-white' : 'rounded-bl-md border-slate-200 bg-white text-slate-800'}`}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={buttonLabel}
|
||||
title={buttonLabel}
|
||||
disabled={playbackState === 'loading'}
|
||||
onClick={/* 当前回调把用户点击交给可重试的异步播放流程。 */ () => void handleToggle()}
|
||||
className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-wait ${outgoing ? 'bg-white text-sky-600 hover:bg-sky-50 focus-visible:ring-white' : 'bg-sky-50 text-sky-600 hover:bg-sky-100 focus-visible:ring-sky-400'}`}
|
||||
>
|
||||
{playbackState === 'loading' ? <Loader2 className="h-4 w-4 animate-spin" />
|
||||
: playbackState === 'playing' ? <Pause className="h-4 w-4 fill-current" />
|
||||
: playbackState === 'error' ? <RotateCcw className="h-4 w-4" />
|
||||
: <Play className="ml-px h-4 w-4 fill-current" />}
|
||||
</button>
|
||||
<div className="min-w-0 flex flex-1 items-center gap-2">
|
||||
<div className="flex h-5 flex-1 items-center gap-0.5" aria-hidden="true">
|
||||
{waveformBars.map(/* barHeight 和 barIndex 分别决定稳定波形柱的像素高度与 React 键。 */ (barHeight, barIndex) => (
|
||||
<span
|
||||
key={`${messageKey}-${barIndex}`}
|
||||
className={`w-0.5 rounded-full ${playbackState === 'playing' ? 'animate-pulse' : ''} ${outgoing ? 'bg-sky-100' : playbackState === 'error' ? 'bg-red-300' : 'bg-sky-400'}`}
|
||||
style={{ height: `${barHeight}px`, animationDelay: `${barIndex * 45}ms` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<span className={`shrink-0 font-mono text-[11px] font-semibold tabular-nums ${outgoing ? 'text-sky-100' : playbackState === 'error' ? 'text-red-500' : 'text-slate-500'}`}>{timeLabel}</span>
|
||||
<span className="sr-only">{statusLabel}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
// @vitest-environment jsdom
|
||||
import { fireEvent,render,screen,within } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import ChatMetadataFeature from './ChatMetadataFeature';
|
||||
import { useChatMetadata } from '../metadata';
|
||||
import type { ChatMetadataState } from '../metadata';
|
||||
import type { ChatQuickReply,ChatSession } from '../models';
|
||||
|
||||
vi.mock('../metadata', /* chatMetadataMockFactory 为抽屉组件交互测试提供受控的元数据 Hook 替身。 */ () => ({ useChatMetadata: vi.fn() }));
|
||||
|
||||
// useChatMetadataMock 是可为每个测试设置返回状态的元数据 Hook 替身。
|
||||
const useChatMetadataMock = vi.mocked(useChatMetadata);
|
||||
// quickReplyFixture 是用于验证操作顺序和关闭行为的账号级快捷回复。
|
||||
const quickReplyFixture: ChatQuickReply = { id: 1, account_id: 'account-1', content: '测试话术', created_at: 1 };
|
||||
// sessionFixture 是使快捷回复发送按钮可用的当前聊天会话。
|
||||
const sessionFixture: ChatSession = { account_id: 'account-1', chat_id: 'chat-1', buyer_id: 'buyer-1', buyer_name: '买家', last_message: '', last_message_at: 1, unread_count: 0 };
|
||||
|
||||
/** metadataFixture 构造抽屉组件交互所需的完整元数据状态,并允许测试观测复制动作。 */
|
||||
const metadataFixture = (copyQuickReply: ChatMetadataState['copyQuickReply']): ChatMetadataState => ({
|
||||
quickReplies: [quickReplyFixture], quickReplyDraft: '', setQuickReplyDraft: vi.fn(), quickReplyBusy: false,
|
||||
pendingDeleteQuickReply: null, requestQuickReplyDelete: vi.fn(), cancelQuickReplyDelete: vi.fn(), confirmQuickReplyDelete: vi.fn().mockResolvedValue(undefined),
|
||||
addQuickReply: vi.fn().mockResolvedValue(undefined), copyQuickReply, copiedQuickReplyID: null, buyerNote: null, noteLoading: false,
|
||||
noteDialogOpen: false, noteEditing: false, noteDraft: '', setNoteDraft: vi.fn(), noteSaving: false, openNoteDialog: vi.fn(),
|
||||
closeNoteDialog: vi.fn(), beginNoteEditing: vi.fn(), saveBuyerNote: vi.fn().mockResolvedValue(undefined), metadataError: '', clearMetadataError: vi.fn(),
|
||||
});
|
||||
|
||||
describe('ChatMetadataFeature', /* 当前回调验证快捷回复抽屉的操作排序和关闭交互。 */ () => {
|
||||
beforeEach(/* 当前回调在每个抽屉交互场景前重置 Hook 替身调用记录。 */ () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test('删除、复制、发送排序正确,复制发送和外部点击均收起抽屉', /* 当前回调验证快捷回复操作的高频关闭流程。 */ async () => {
|
||||
// copyQuickReply 保存可观测的复制动作替身。
|
||||
const copyQuickReply = vi.fn().mockResolvedValue(undefined);
|
||||
// closeQuickReplyPanel 保存抽屉关闭动作替身。
|
||||
const closeQuickReplyPanel = vi.fn();
|
||||
// sendQuickReply 保存当前会话模板发送动作替身。
|
||||
const sendQuickReply = vi.fn().mockResolvedValue(undefined);
|
||||
useChatMetadataMock.mockReturnValue(metadataFixture(copyQuickReply));
|
||||
render(<><ChatMetadataFeature activeAccountID="account-1" selectedSession={sessionFixture} quickReplyPanelOpen closeQuickReplyPanel={closeQuickReplyPanel} sendQuickReply={sendQuickReply} sending={false} accountOnline /><button type="button">抽屉外区域</button></>);
|
||||
// replyCard 是包含当前快捷回复操作按钮的卡片元素。
|
||||
const replyCard = screen.getByText('测试话术').closest('article');
|
||||
if (replyCard == null) throw new Error('未找到快捷回复卡片');
|
||||
// actionNames 保存卡片内按钮按视觉顺序的可访问名称。
|
||||
const actionNames = within(replyCard).getAllByRole('button').map(/* actionButton 保存当前待检查的快捷回复操作按钮。 */ actionButton => actionButton.getAttribute('aria-label') || actionButton.textContent);
|
||||
expect(actionNames).toEqual(['删除快捷回复', '复制', '发送']);
|
||||
fireEvent.click(within(replyCard).getByRole('button', { name: '复制' }));
|
||||
expect(copyQuickReply).toHaveBeenCalledWith(quickReplyFixture);
|
||||
expect(closeQuickReplyPanel).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(within(replyCard).getByRole('button', { name: '发送' }));
|
||||
expect(sendQuickReply).toHaveBeenCalledWith('测试话术');
|
||||
expect(closeQuickReplyPanel).toHaveBeenCalledTimes(2);
|
||||
fireEvent.pointerDown(screen.getByRole('button', { name: '抽屉外区域' }));
|
||||
expect(closeQuickReplyPanel).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Clipboard,FilePenLine,Plus,Send,Trash2,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useChatMetadata } from '../metadata';
|
||||
import type { ChatSession } from '../models';
|
||||
|
||||
/** ChatMetadataFeatureProps 描述独立构建的聊天元数据控件所需上下文与外部发送能力。 */
|
||||
type ChatMetadataFeatureProps = {
|
||||
/** activeAccountID 是当前选中的闲鱼账号标识。 */
|
||||
activeAccountID: string;
|
||||
/** selectedSession 是当前正在查看的聊天会话。 */
|
||||
selectedSession: ChatSession | undefined;
|
||||
/** quickReplyPanelOpen 控制右侧快捷回复抽屉是否可见。 */
|
||||
quickReplyPanelOpen: boolean;
|
||||
/** closeQuickReplyPanel 收起右侧快捷回复抽屉。 */
|
||||
closeQuickReplyPanel: () => void;
|
||||
/** sendQuickReply 将模板文本交给既有可靠聊天发送流程。 */
|
||||
sendQuickReply: (content: string) => Promise<void>;
|
||||
/** sending 表示当前聊天发送请求是否进行中。 */
|
||||
sending: boolean;
|
||||
/** accountOnline 表示当前账号是否可以向平台发送消息。 */
|
||||
accountOnline: boolean;
|
||||
};
|
||||
|
||||
/** ChatMetadataFeature 提供账号快捷回复和买家备注交互,并由独立构建分片控制聊天页面体积。 */
|
||||
const ChatMetadataFeature: React.FC<ChatMetadataFeatureProps> = ({ activeAccountID, selectedSession, quickReplyPanelOpen, closeQuickReplyPanel, sendQuickReply, sending, accountOnline }) => {
|
||||
// chatMetadata 保存账号快捷回复和当前买家备注的独立数据、取消控制及 UI 交互状态。
|
||||
const chatMetadata = useChatMetadata(activeAccountID, selectedSession);
|
||||
// buyerNoteContent 保存未经字符截断的完整备注;展示区域仅依标题栏的两行空间裁切可见文本。
|
||||
const buyerNoteContent = chatMetadata.buyerNote?.content.trim() || '';
|
||||
// quickReplyPanelRef 指向快捷回复抽屉根节点,用于区分抽屉内交互与页面外点击。
|
||||
const quickReplyPanelRef = React.useRef<HTMLElement | null>(null);
|
||||
|
||||
React.useEffect(/* 当前副作用在抽屉展开期间监听页面级指针事件,点击抽屉外部时自动收起并在 cleanup 中移除监听。 */ () => {
|
||||
if (!quickReplyPanelOpen) return undefined;
|
||||
/** closeWhenClickOutside 仅在指针目标不属于快捷回复抽屉时收起面板。 */
|
||||
const closeWhenClickOutside = (event: PointerEvent): void => {
|
||||
// eventTarget 保存当前指针事件的目标节点;非 DOM 节点不参与抽屉内外判断。
|
||||
const eventTarget = event.target;
|
||||
if (!(eventTarget instanceof Node) || quickReplyPanelRef.current?.contains(eventTarget)) return;
|
||||
closeQuickReplyPanel();
|
||||
};
|
||||
document.addEventListener('pointerdown', closeWhenClickOutside);
|
||||
return /* 当前 cleanup 在抽屉收起或组件卸载时移除页面级监听。 */ () => document.removeEventListener('pointerdown', closeWhenClickOutside);
|
||||
}, [closeQuickReplyPanel, quickReplyPanelOpen]);
|
||||
|
||||
return <>
|
||||
{selectedSession && <div className="absolute left-40 right-[5.5rem] top-2 z-10 flex min-h-16 items-center justify-center">
|
||||
<button type="button" onClick={/* 当前回调打开当前买家的完整备注弹窗。 */ chatMetadata.openNoteDialog} className="inline-flex w-fit max-w-full items-center gap-2 rounded-lg border border-transparent px-2.5 py-1.5 text-left text-xs font-medium leading-5 text-slate-500 transition hover:border-sky-100 hover:bg-sky-50 hover:text-sky-700" title={buyerNoteContent || '添加用户备注'}>
|
||||
<FilePenLine className="h-4 w-4 shrink-0 self-center text-slate-400" />
|
||||
<span className="min-w-0 break-words line-clamp-2">{chatMetadata.noteLoading ? '正在读取备注…' : buyerNoteContent || '添加用户备注'}</span>
|
||||
</button>
|
||||
</div>}
|
||||
{quickReplyPanelOpen && activeAccountID && <aside ref={quickReplyPanelRef} aria-label="账号快捷回复" className="absolute inset-y-0 right-0 z-20 flex w-[304px] max-w-[88%] flex-col border-l border-slate-200 bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-slate-100 px-4 py-3">
|
||||
<div>
|
||||
<div className="text-sm font-black text-slate-900">快捷回复</div>
|
||||
<div className="mt-0.5 text-[11px] font-medium text-slate-400">当前账号 · {chatMetadata.quickReplies.length}/50</div>
|
||||
</div>
|
||||
<button type="button" onClick={/* 当前回调收起右侧快捷回复抽屉。 */ closeQuickReplyPanel} className="rounded-lg p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-700" aria-label="收起快捷回复"><X className="h-4 w-4" /></button>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto p-3">
|
||||
{chatMetadata.quickReplies.map(/* reply 保存当前待展示的账号级快捷回复。 */ reply => <article key={reply.id} className="rounded-xl border border-slate-200 bg-slate-50/70 p-3 transition hover:border-sky-200 hover:bg-sky-50/40">
|
||||
<p className="whitespace-pre-wrap break-words text-xs leading-5 text-slate-700">{reply.content}</p>
|
||||
<div className="mt-2 flex items-center justify-end gap-1">
|
||||
<button type="button" onClick={/* 当前回调请求确认删除本条快捷回复。 */ () => chatMetadata.requestQuickReplyDelete(reply)} disabled={chatMetadata.quickReplyBusy} className="rounded-lg p-1 text-slate-400 transition hover:bg-red-50 hover:text-red-600 disabled:opacity-40" aria-label="删除快捷回复"><Trash2 className="h-3.5 w-3.5" /></button>
|
||||
<button type="button" onClick={/* 当前回调复制本条快捷回复后收起抽屉。 */ () => { closeQuickReplyPanel(); void chatMetadata.copyQuickReply(reply); }} className="rounded-lg px-2 py-1 text-[11px] font-bold text-slate-500 transition hover:bg-white hover:text-sky-700" title="复制快捷回复"><Clipboard className="mr-1 inline h-3 w-3" />{chatMetadata.copiedQuickReplyID === reply.id ? '已复制' : '复制'}</button>
|
||||
<button type="button" onClick={/* 当前回调发送本条快捷回复后收起抽屉。 */ () => { closeQuickReplyPanel(); void sendQuickReply(reply.content); }} disabled={!selectedSession || sending || !accountOnline} className="rounded-lg bg-sky-500 px-2 py-1 text-[11px] font-bold text-white transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300" title="发送快捷回复"><Send className="mr-1 inline h-3 w-3" />发送</button>
|
||||
</div>
|
||||
</article>)}
|
||||
{chatMetadata.quickReplies.length === 0 && <div className="px-5 py-12 text-center text-xs leading-5 text-slate-400">还没有快捷回复。把常用话术添加在下方,当前账号的所有聊天都可以使用。</div>}
|
||||
</div>
|
||||
<div className="border-t border-slate-200 bg-slate-50/80 p-3">
|
||||
{chatMetadata.metadataError && <div className="mb-2 flex items-start justify-between gap-2 rounded-lg bg-red-50 px-2.5 py-2 text-[11px] leading-4 text-red-700"><span>{chatMetadata.metadataError}</span><button type="button" onClick={/* 当前回调关闭当前快捷回复或备注错误提示。 */ chatMetadata.clearMetadataError} className="shrink-0" aria-label="关闭错误提示"><X className="h-3.5 w-3.5" /></button></div>}
|
||||
<textarea value={chatMetadata.quickReplyDraft} onChange={/* 当前回调更新新增快捷回复表单文本。 */ event => chatMetadata.setQuickReplyDraft(event.target.value)} onKeyDown={/* 当前回调支持 Enter 添加、Shift Enter 换行的快捷回复输入。 */ event => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void chatMetadata.addQuickReply(); } }} rows={2} maxLength={2000} placeholder="添加常用快捷回复…" className="min-h-14 w-full resize-none rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs leading-5 outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
|
||||
<button type="button" onClick={/* 当前回调保存底部输入框中的快捷回复。 */ () => void chatMetadata.addQuickReply()} disabled={!chatMetadata.quickReplyDraft.trim() || chatMetadata.quickReplyBusy || chatMetadata.quickReplies.length >= 50} className="mt-2 flex w-full items-center justify-center gap-1.5 rounded-xl bg-slate-900 py-2 text-xs font-bold text-white transition hover:bg-slate-700 disabled:cursor-not-allowed disabled:bg-slate-300"><Plus className="h-3.5 w-3.5" />添加快捷回复</button>
|
||||
</div>
|
||||
</aside>}
|
||||
{chatMetadata.noteDialogOpen && <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/50 p-4" onClick={/* 当前回调点击遮罩关闭买家备注弹窗。 */ chatMetadata.closeNoteDialog}>
|
||||
<div role="dialog" aria-modal="true" aria-labelledby="buyer-note-title" className="flex max-h-[82vh] w-full max-w-lg flex-col overflow-hidden rounded-2xl bg-white shadow-2xl" onClick={/* 当前回调阻止备注内容点击冒泡到遮罩。 */ event => event.stopPropagation()}>
|
||||
<div className="flex items-center justify-between border-b border-slate-200 px-5 py-4"><div className="min-w-0"><div id="buyer-note-title" className="text-sm font-black text-slate-900">用户备注</div><div className="mt-0.5 truncate text-xs text-slate-400">{selectedSession?.buyer_name || selectedSession?.buyer_id || '当前用户'} · ID {selectedSession?.buyer_id || '-'}</div></div><button type="button" onClick={/* 当前回调关闭买家备注弹窗。 */ chatMetadata.closeNoteDialog} className="rounded-lg p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-700" aria-label="关闭备注"><X className="h-5 w-5" /></button></div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-5">{chatMetadata.metadataError && <div className="mb-4 flex items-start justify-between gap-2 rounded-xl bg-red-50 px-3 py-2.5 text-xs leading-5 text-red-700"><span>{chatMetadata.metadataError}</span><button type="button" onClick={/* 当前回调关闭当前快捷回复或备注错误提示。 */ chatMetadata.clearMetadataError} aria-label="关闭错误提示"><X className="h-4 w-4" /></button></div>}{chatMetadata.noteEditing ? <textarea autoFocus value={chatMetadata.noteDraft} onChange={/* 当前回调更新买家备注编辑表单。 */ event => chatMetadata.setNoteDraft(event.target.value)} maxLength={2000} rows={10} placeholder="记录该用户的沟通偏好、需求或重要事项…" className="min-h-52 w-full resize-y rounded-xl border border-slate-200 bg-slate-50 px-3 py-3 text-sm leading-6 outline-none transition focus:border-sky-400 focus:bg-white focus:ring-2 focus:ring-sky-100" /> : <div className="min-h-40 whitespace-pre-wrap break-words rounded-xl border border-slate-100 bg-slate-50/80 px-4 py-3 text-sm leading-6 text-slate-700">{chatMetadata.buyerNote?.content || '尚未添加备注。点击“编辑”即可记录该用户的信息。'}</div>}</div>
|
||||
<div className="flex items-center justify-end gap-2 border-t border-slate-200 px-5 py-3">{chatMetadata.noteEditing ? <><button type="button" onClick={/* 当前回调关闭备注弹窗并放弃未保存变更。 */ chatMetadata.closeNoteDialog} disabled={chatMetadata.noteSaving} className="rounded-xl px-4 py-2 text-sm font-bold text-slate-600 transition hover:bg-slate-100 disabled:opacity-50">取消</button><button type="button" onClick={/* 当前回调保存当前买家备注表单。 */ () => void chatMetadata.saveBuyerNote()} disabled={chatMetadata.noteSaving} className="rounded-xl bg-sky-500 px-4 py-2 text-sm font-bold text-white shadow-sm transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300">{chatMetadata.noteSaving ? '保存中…' : '保存'}</button></> : <button type="button" onClick={/* 当前回调将备注弹窗切换为编辑模式。 */ chatMetadata.beginNoteEditing} className="rounded-xl bg-sky-500 px-4 py-2 text-sm font-bold text-white shadow-sm transition hover:bg-sky-600">编辑</button>}</div>
|
||||
</div>
|
||||
</div>}
|
||||
{chatMetadata.pendingDeleteQuickReply && <div className="fixed inset-0 z-[60] flex items-center justify-center bg-slate-950/50 p-4" onClick={/* 当前回调点击遮罩放弃快捷回复删除。 */ chatMetadata.cancelQuickReplyDelete}><div role="alertdialog" aria-modal="true" aria-labelledby="quick-reply-delete-title" className="w-full max-w-sm rounded-2xl bg-white p-5 shadow-2xl" onClick={/* 当前回调阻止删除确认内容点击冒泡到遮罩。 */ event => event.stopPropagation()}><div id="quick-reply-delete-title" className="text-base font-black text-slate-900">删除快捷回复?</div><p className="mt-2 whitespace-pre-wrap break-words text-sm leading-6 text-slate-500">“{chatMetadata.pendingDeleteQuickReply.content}” 将从当前账号的快捷回复中移除。</p><div className="mt-5 flex justify-end gap-2"><button type="button" onClick={/* 当前回调关闭快捷回复删除确认框。 */ chatMetadata.cancelQuickReplyDelete} disabled={chatMetadata.quickReplyBusy} className="rounded-xl px-4 py-2 text-sm font-bold text-slate-600 transition hover:bg-slate-100 disabled:opacity-50">取消</button><button type="button" onClick={/* 当前回调确认并删除快捷回复。 */ () => void chatMetadata.confirmQuickReplyDelete()} disabled={chatMetadata.quickReplyBusy} className="rounded-xl bg-red-500 px-4 py-2 text-sm font-bold text-white transition hover:bg-red-600 disabled:cursor-not-allowed disabled:bg-red-300">{chatMetadata.quickReplyBusy ? '删除中…' : '删除'}</button></div></div></div>}
|
||||
</>;
|
||||
};
|
||||
|
||||
export default ChatMetadataFeature;
|
||||
@@ -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 '../../../shared/api-contract/chat';
|
||||
import type { AccountDetail,ChatMessage,ChatSession } from './api';
|
||||
import { getAccountDetails,getAccountRuntimeStatuses,getChatMessagePage,getChatSessionPage,markChatRead,sendChatImage,sendChatMessage } from './api';
|
||||
import { useChat } from './hooks';
|
||||
import { publishChatConnectionState,publishChatLiveMessage } from './liveEvents';
|
||||
@@ -99,6 +99,17 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
expect(sendMessageMock).toHaveBeenCalledWith(expect.objectContaining({ text: '回复内容', chat_id: 'chat-1' }), expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(hook.result.current.messages).toContainEqual(sentMessageFixture);
|
||||
|
||||
await act(
|
||||
// retainedDraftAction 写入一段不应被快捷回复发送清空的普通消息草稿。
|
||||
() => hook.result.current.setDraft('仍在编辑的草稿'),
|
||||
);
|
||||
await act(
|
||||
// quickReplyAction 发送账号快捷回复,复用可靠发送但保留普通草稿。
|
||||
async () => hook.result.current.handleQuickReply('快捷回复内容'),
|
||||
);
|
||||
expect(sendMessageMock).toHaveBeenLastCalledWith(expect.objectContaining({ text: '快捷回复内容', chat_id: 'chat-1' }), expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(hook.result.current.draft).toBe('仍在编辑的草稿');
|
||||
|
||||
await act(
|
||||
// imageAction 提交图片消息。
|
||||
async () => hook.result.current.handleImage(new File(['image'], 'image.png', { type: 'image/png' })),
|
||||
|
||||
@@ -49,6 +49,8 @@ export type UseChatResult = ChatFeatureState & {
|
||||
handleMessageScroll: () => void;
|
||||
/** 发送文本消息。 */
|
||||
handleSend: () => Promise<void>;
|
||||
/** 发送快捷回复且保留正在编辑的普通消息草稿。 */
|
||||
handleQuickReply: (content: string) => Promise<void>;
|
||||
/** 发送图片消息。 */
|
||||
handleImage: (file?: File) => Promise<void>;
|
||||
/** 从剪贴板候选文件中选择首张图片进入预览。 */
|
||||
@@ -508,7 +510,7 @@ export const useChat = (): UseChatResult => {
|
||||
}, [activeAccountID, contactCursors, contactsLoading, hasMoreContacts]);
|
||||
|
||||
/** 发送文本消息并记录失败重试数据。 */
|
||||
const sendText = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (text: string, rememberRetry: boolean): Promise<void> => {
|
||||
const sendText = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (text: string, rememberRetry: boolean, clearDraft: boolean): Promise<void> => {
|
||||
if (!selectedSession || !activeAccountID || sending) return;
|
||||
// sequence 请求序号。
|
||||
const sequence = ++sendSequence.current;
|
||||
@@ -522,7 +524,7 @@ export const useChat = (): UseChatResult => {
|
||||
// result 处理结果。
|
||||
const result = await sendChatMessage({ account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id, buyer_name: selectedSession.buyer_name, item_id: selectedSession.item_id, item_title: selectedSession.item_title, text }, { signal: controller.signal });
|
||||
if (!isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) return;
|
||||
setDraft('');
|
||||
if (clearDraft) setDraft('');
|
||||
setRetryText(null);
|
||||
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeLiveMessage(current, result.message));
|
||||
} catch (/* sendError 表示发送错误。 */ sendError) {
|
||||
@@ -570,9 +572,17 @@ export const useChat = (): UseChatResult => {
|
||||
// text 文本。
|
||||
const text = draft.trim();
|
||||
if (!text || !selectedSession || !activeAccountID || sending) return;
|
||||
await sendText(text, true);
|
||||
await sendText(text, true, true);
|
||||
}, [activeAccountID, draft, selectedSession, sendText, sending]);
|
||||
|
||||
/** 发送侧栏快捷回复,并在成功后保留用户尚未发送的普通草稿。 */
|
||||
const handleQuickReply = useCallback(/* 当前回调将账号级快捷回复交给既有可靠文本发送流程。 */ async (content: string): Promise<void> => {
|
||||
// text 保存去除首尾空白后的快捷回复正文,避免空模板触发发送请求。
|
||||
const text = content.trim();
|
||||
if (!text || !selectedSession || !activeAccountID || sending) return;
|
||||
await sendText(text, true, false);
|
||||
}, [activeAccountID, selectedSession, sendText, sending]);
|
||||
|
||||
/** 处理图片选择并进入确认预览,不直接触发平台发送。 */
|
||||
const handleImage = useCallback(/* 当前回调接收文件选择结果并创建图片预览。 */ async (file?: File): Promise<void> => {
|
||||
if (!file || !selectedSession || !activeAccountID || sending) return;
|
||||
@@ -608,14 +618,14 @@ export const useChat = (): UseChatResult => {
|
||||
|
||||
/** 重试最近一次失败的文本或图片发送。 */
|
||||
const retrySend = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||
if (retryText) await sendText(retryText, false);
|
||||
if (retryText) await sendText(retryText, false, true);
|
||||
else if (retryImage) await sendImage(retryImage, false);
|
||||
}, [retryImage, retryText, sendImage, sendText]);
|
||||
|
||||
return {
|
||||
accounts, activeAccountID, activeSessions, selectedSession, activeAccount, messages, search, unreadOnly, draft, loading, messagesLoading, olderLoading, hasOlder, contactsLoading, hasMoreContacts: hasMoreContacts[activeAccountID] === true, emojiOpen, sending, error, liveState, pendingImage,
|
||||
activeChatID, filteredSessions, scrollRef, imageInputRef, setActiveAccountID, setActiveChatID, setSearch, setUnreadOnly, setDraft, setEmojiOpen,
|
||||
reloadSessions, loadMoreContacts, loadOlderMessages, handleMessageScroll, handleSend, handleImage, handlePastedImages, confirmSendImage, closeImagePreview, retrySend, retryAvailable: Boolean(retryText || retryImage), unreadForAccount,
|
||||
reloadSessions, loadMoreContacts, loadOlderMessages, handleMessageScroll, handleSend, handleQuickReply, handleImage, handlePastedImages, confirmSendImage, closeImagePreview, retrySend, retryAvailable: Boolean(retryText || retryImage), unreadForAccount,
|
||||
emojiURL, xianyuEmojis, renderXianyuText, formatClock, messageTime,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import { createChatQuickReply,deleteChatQuickReply,getChatBuyerNote,getChatQuickReplies,saveChatBuyerNote } from './api';
|
||||
import { useChatMetadata } from './metadata';
|
||||
import type { ChatSession } from './models';
|
||||
|
||||
vi.mock('./api', /* chatMetadataApiMockFactory 提供快捷回复和买家备注 Hook 的确定性 API 替身。 */ () => ({
|
||||
createChatQuickReply: vi.fn(),
|
||||
deleteChatQuickReply: vi.fn(),
|
||||
getChatBuyerNote: vi.fn(),
|
||||
getChatQuickReplies: vi.fn(),
|
||||
saveChatBuyerNote: vi.fn(),
|
||||
}));
|
||||
|
||||
// createQuickReplyMock 是创建快捷回复请求的可控替身。
|
||||
const createQuickReplyMock = vi.mocked(createChatQuickReply);
|
||||
// deleteQuickReplyMock 是删除快捷回复请求的可控替身。
|
||||
const deleteQuickReplyMock = vi.mocked(deleteChatQuickReply);
|
||||
// getBuyerNoteMock 是读取买家备注请求的可控替身。
|
||||
const getBuyerNoteMock = vi.mocked(getChatBuyerNote);
|
||||
// getQuickRepliesMock 是读取账号快捷回复请求的可控替身。
|
||||
const getQuickRepliesMock = vi.mocked(getChatQuickReplies);
|
||||
// saveBuyerNoteMock 是保存买家备注请求的可控替身。
|
||||
const saveBuyerNoteMock = vi.mocked(saveChatBuyerNote);
|
||||
|
||||
// sessionFixture 是当前账号下供备注隔离测试使用的会话摘要。
|
||||
const sessionFixture: ChatSession = { account_id: 'account-1', chat_id: 'chat-1', buyer_id: 'buyer-1', buyer_name: '买家', last_message: '', last_message_at: 1, unread_count: 0 };
|
||||
|
||||
/** QuickReplyFixture 是延迟响应测试使用的最小快捷回复形状。 */
|
||||
type QuickReplyFixture = {
|
||||
/** id 是快捷回复稳定标识。 */
|
||||
id: number;
|
||||
/** account_id 是快捷回复所属账号。 */
|
||||
account_id: string;
|
||||
/** content 是快捷回复文本模板。 */
|
||||
content: string;
|
||||
/** created_at 是快捷回复创建时间。 */
|
||||
created_at: number;
|
||||
};
|
||||
|
||||
/** MetadataHookProps 是可重渲染元数据 Hook 的账号与会话输入。 */
|
||||
type MetadataHookProps = {
|
||||
/** accountID 是当前选择的闲鱼账号标识。 */
|
||||
accountID: string;
|
||||
/** session 是当前选中会话;缺失时不查询买家备注。 */
|
||||
session: ChatSession | undefined;
|
||||
};
|
||||
|
||||
describe('useChatMetadata', /* 当前回调覆盖账号快捷回复与买家备注的异步状态和用户交互。 */ () => {
|
||||
beforeEach(/* 当前回调重置所有元数据 API 替身并配置默认成功响应。 */ () => {
|
||||
vi.clearAllMocks();
|
||||
getQuickRepliesMock.mockResolvedValue([{ id: 1, account_id: 'account-1', content: '您好', created_at: 1 }]);
|
||||
getBuyerNoteMock.mockResolvedValue({ account_id: 'account-1', buyer_id: 'buyer-1', content: '偏好顺丰', updated_at: 1 });
|
||||
createQuickReplyMock.mockResolvedValue({ id: 2, account_id: 'account-1', content: '现货可拍', created_at: 2 });
|
||||
deleteQuickReplyMock.mockResolvedValue({ success: true });
|
||||
saveBuyerNoteMock.mockResolvedValue({ account_id: 'account-1', buyer_id: 'buyer-1', content: '重点客户', updated_at: 2 });
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: vi.fn().mockResolvedValue(undefined) } });
|
||||
});
|
||||
|
||||
test('新增、复制和确认删除快捷回复,且保存买家备注', /* 当前回调验证元数据常用成功路径与编辑状态分离。 */ async () => {
|
||||
// hook 是聊天元数据 Hook 的渲染结果。
|
||||
const hook = renderHook(
|
||||
// metadataHookFactory 以稳定账号和会话创建元数据 Hook。
|
||||
() => useChatMetadata('account-1', sessionFixture),
|
||||
);
|
||||
await waitFor(
|
||||
// dataAssertion 等待账号快捷回复和买家备注的初始请求完成。
|
||||
() => expect(hook.result.current.quickReplies).toHaveLength(1),
|
||||
);
|
||||
expect(hook.result.current.buyerNote?.content).toBe('偏好顺丰');
|
||||
await act(
|
||||
// draftAction 写入新增快捷回复输入框。
|
||||
() => hook.result.current.setQuickReplyDraft('现货可拍'),
|
||||
);
|
||||
await act(
|
||||
// addAction 创建新的账号快捷回复。
|
||||
async () => hook.result.current.addQuickReply(),
|
||||
);
|
||||
expect(createQuickReplyMock).toHaveBeenCalledWith('account-1', '现货可拍');
|
||||
expect(hook.result.current.quickReplies.map(/* reply 保存当前列表中的快捷回复。 */ reply => reply.id)).toEqual([2, 1]);
|
||||
await act(
|
||||
// copyAction 将新创建快捷回复复制到系统剪贴板。
|
||||
async () => hook.result.current.copyQuickReply(hook.result.current.quickReplies[0]),
|
||||
);
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('现货可拍');
|
||||
await act(
|
||||
// openDeleteAction 打开新创建快捷回复的删除确认状态。
|
||||
() => hook.result.current.requestQuickReplyDelete(hook.result.current.quickReplies[0]),
|
||||
);
|
||||
await act(
|
||||
// deleteAction 确认并删除当前待确认快捷回复。
|
||||
async () => hook.result.current.confirmQuickReplyDelete(),
|
||||
);
|
||||
expect(deleteQuickReplyMock).toHaveBeenCalledWith('account-1', 2);
|
||||
expect(hook.result.current.quickReplies.map(/* reply 保存删除后剩余的快捷回复。 */ reply => reply.id)).toEqual([1]);
|
||||
await act(
|
||||
// openNoteAction 打开默认只读的买家备注弹窗。
|
||||
() => hook.result.current.openNoteDialog(),
|
||||
);
|
||||
expect(hook.result.current.noteEditing).toBe(false);
|
||||
await act(
|
||||
// editNoteAction 进入备注编辑态并填写新的文本。
|
||||
() => { hook.result.current.beginNoteEditing(); hook.result.current.setNoteDraft('重点客户'); },
|
||||
);
|
||||
await act(
|
||||
// saveNoteAction 保存当前买家备注。
|
||||
async () => hook.result.current.saveBuyerNote(),
|
||||
);
|
||||
expect(saveBuyerNoteMock).toHaveBeenCalledWith('account-1', 'buyer-1', '重点客户');
|
||||
expect(hook.result.current.buyerNote?.content).toBe('重点客户');
|
||||
expect(hook.result.current.noteEditing).toBe(false);
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('账号切换后拒绝旧快捷回复响应', /* 当前回调验证请求代次保护不会让慢旧响应覆盖新账号。 */ async () => {
|
||||
// resolveOldReplies 保存稍后手动完成旧账号请求的 Promise 解析函数。
|
||||
let resolveOldReplies: ((replies: QuickReplyFixture[]) => void) | undefined;
|
||||
// oldRepliesPromise 是模拟慢旧账号快捷回复请求的受控 Promise。
|
||||
const oldRepliesPromise = new Promise<QuickReplyFixture[]>(/* resolve 保存外部可调用的旧请求完成函数。 */ resolve => { resolveOldReplies = resolve; });
|
||||
getQuickRepliesMock.mockImplementationOnce(/* 当前回调让首次账号请求保持 pending,模拟网络晚到。 */ () => oldRepliesPromise).mockResolvedValueOnce([{ id: 9, account_id: 'account-2', content: '新账号回复', created_at: 1 }]);
|
||||
// hook 是可通过 rerender 切换账号的聊天元数据 Hook。
|
||||
const hook = renderHook(
|
||||
// metadataHookFactory 根据渲染参数创建元数据 Hook。
|
||||
// props 保存当前账号和选中会话的测试输入。
|
||||
({ accountID, session }: MetadataHookProps) => useChatMetadata(accountID, session),
|
||||
{ initialProps: { accountID: 'account-1', session: sessionFixture } },
|
||||
);
|
||||
hook.rerender({ accountID: 'account-2', session: { ...sessionFixture, account_id: 'account-2', buyer_id: 'buyer-2' } });
|
||||
await waitFor(
|
||||
// newAccountAssertion 等待新账号请求先写入列表。
|
||||
() => expect(hook.result.current.quickReplies[0]?.id).toBe(9),
|
||||
);
|
||||
await act(
|
||||
// oldResponseAction 在新账号已生效后完成旧账号请求。
|
||||
() => resolveOldReplies?.([{ id: 8, account_id: 'account-1', content: '旧账号回复', created_at: 1 }]),
|
||||
);
|
||||
expect(hook.result.current.quickReplies[0]?.id).toBe(9);
|
||||
hook.unmount();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { createChatQuickReply, deleteChatQuickReply, getChatBuyerNote, getChatQuickReplies, saveChatBuyerNote } from './api';
|
||||
import type { ChatBuyerNote, ChatQuickReply, ChatSession } from './models';
|
||||
import { isChatAbortError } from './state';
|
||||
|
||||
/** ChatMetadataState 描述聊天页面中快捷回复与买家备注的短暂 UI 状态和交互动作。 */
|
||||
export type ChatMetadataState = {
|
||||
/** quickReplies 保存当前账号可用的快捷回复。 */
|
||||
quickReplies: ChatQuickReply[];
|
||||
/** quickReplyDraft 保存底部新增快捷回复输入框的表单文本。 */
|
||||
quickReplyDraft: string;
|
||||
/** setQuickReplyDraft 更新新增快捷回复表单文本。 */
|
||||
setQuickReplyDraft: (content: string) => void;
|
||||
/** quickReplyBusy 表示新增或删除快捷回复请求正在进行。 */
|
||||
quickReplyBusy: boolean;
|
||||
/** pendingDeleteQuickReply 保存等待用户确认删除的快捷回复;空值表示未打开确认框。 */
|
||||
pendingDeleteQuickReply: ChatQuickReply | null;
|
||||
/** requestQuickReplyDelete 打开指定快捷回复的删除确认框。 */
|
||||
requestQuickReplyDelete: (reply: ChatQuickReply) => void;
|
||||
/** cancelQuickReplyDelete 关闭删除确认框而不改变数据。 */
|
||||
cancelQuickReplyDelete: () => void;
|
||||
/** confirmQuickReplyDelete 删除已确认的快捷回复。 */
|
||||
confirmQuickReplyDelete: () => Promise<void>;
|
||||
/** addQuickReply 保存底部输入框中的快捷回复。 */
|
||||
addQuickReply: () => Promise<void>;
|
||||
/** copyQuickReply 将一条快捷回复写入系统剪贴板。 */
|
||||
copyQuickReply: (reply: ChatQuickReply) => Promise<void>;
|
||||
/** copiedQuickReplyID 保存最近复制成功的快捷回复标识,用于显示短暂反馈。 */
|
||||
copiedQuickReplyID: number | null;
|
||||
/** buyerNote 保存当前聊天买家的完整备注;无选中会话时为空。 */
|
||||
buyerNote: ChatBuyerNote | null;
|
||||
/** noteLoading 表示当前会话买家备注正在查询。 */
|
||||
noteLoading: boolean;
|
||||
/** noteDialogOpen 控制买家备注弹窗的可见性。 */
|
||||
noteDialogOpen: boolean;
|
||||
/** noteEditing 控制备注弹窗处于只读查看还是编辑状态。 */
|
||||
noteEditing: boolean;
|
||||
/** noteDraft 保存备注弹窗编辑态的表单文本。 */
|
||||
noteDraft: string;
|
||||
/** setNoteDraft 更新备注编辑框的表单文本。 */
|
||||
setNoteDraft: (content: string) => void;
|
||||
/** noteSaving 表示备注保存请求正在进行。 */
|
||||
noteSaving: boolean;
|
||||
/** openNoteDialog 打开完整备注弹窗并默认显示只读内容。 */
|
||||
openNoteDialog: () => void;
|
||||
/** closeNoteDialog 关闭备注弹窗并放弃未保存表单变更。 */
|
||||
closeNoteDialog: () => void;
|
||||
/** beginNoteEditing 将备注弹窗切换为编辑态。 */
|
||||
beginNoteEditing: () => void;
|
||||
/** saveBuyerNote 保存当前买家备注。 */
|
||||
saveBuyerNote: () => Promise<void>;
|
||||
/** metadataError 保存快捷回复或买家备注操作的最近用户可见错误。 */
|
||||
metadataError: string;
|
||||
/** clearMetadataError 清除当前元数据错误提示。 */
|
||||
clearMetadataError: () => void;
|
||||
};
|
||||
|
||||
/** useChatMetadata 管理账号级快捷回复及当前会话买家备注,并隔离账号/会话切换后的晚到响应。 */
|
||||
export const useChatMetadata = (activeAccountID: string, selectedSession: ChatSession | undefined): ChatMetadataState => {
|
||||
/** quickReplies 保存当前账号可用的快捷回复;账号切换时以最新请求响应替换。 */
|
||||
const [quickReplies, setQuickReplies] = useState<ChatQuickReply[]>([]);
|
||||
/** quickReplyDraft 保存新增快捷回复的小型输入框文本。 */
|
||||
const [quickReplyDraft, setQuickReplyDraft] = useState('');
|
||||
/** quickReplyBusy 防止新增或删除过程中重复提交快捷回复变更。 */
|
||||
const [quickReplyBusy, setQuickReplyBusy] = useState(false);
|
||||
/** pendingDeleteQuickReply 保存等待确认删除的快捷回复,避免误触即删除。 */
|
||||
const [pendingDeleteQuickReply, setPendingDeleteQuickReply] = useState<ChatQuickReply | null>(null);
|
||||
/** copiedQuickReplyID 保存最近复制成功的回复标识,用于按钮内的短暂成功反馈。 */
|
||||
const [copiedQuickReplyID, setCopiedQuickReplyID] = useState<number | null>(null);
|
||||
/** buyerNote 保存当前账号和买家组合对应的完整备注。 */
|
||||
const [buyerNote, setBuyerNote] = useState<ChatBuyerNote | null>(null);
|
||||
/** noteLoading 表示当前会话的买家备注仍在读取。 */
|
||||
const [noteLoading, setNoteLoading] = useState(false);
|
||||
/** noteDialogOpen 控制完整买家备注弹窗显示。 */
|
||||
const [noteDialogOpen, setNoteDialogOpen] = useState(false);
|
||||
/** noteEditing 控制备注弹窗是否显示可写表单。 */
|
||||
const [noteEditing, setNoteEditing] = useState(false);
|
||||
/** noteDraft 保存备注编辑中的表单正文,与服务端数据分离。 */
|
||||
const [noteDraft, setNoteDraft] = useState('');
|
||||
/** noteSaving 防止备注保存期间发生重复提交。 */
|
||||
const [noteSaving, setNoteSaving] = useState(false);
|
||||
/** metadataError 保存元数据请求失败的用户可见说明。 */
|
||||
const [metadataError, setMetadataError] = useState('');
|
||||
/** quickReplyControllerRef 保存当前账号快捷回复读取请求的取消控制器。 */
|
||||
const quickReplyControllerRef = useRef<AbortController | null>(null);
|
||||
/** quickReplySequenceRef 为账号快捷回复查询分配单调递增代次,阻止晚到响应覆盖新账号。 */
|
||||
const quickReplySequenceRef = useRef(0);
|
||||
/** noteControllerRef 保存当前买家备注读取请求的取消控制器。 */
|
||||
const noteControllerRef = useRef<AbortController | null>(null);
|
||||
/** noteSequenceRef 为买家备注查询分配单调递增代次,阻止旧会话覆盖新会话。 */
|
||||
const noteSequenceRef = useRef(0);
|
||||
/** copyTimerRef 保存复制反馈自动关闭计时器,卸载时由当前 Hook 清理。 */
|
||||
const copyTimerRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(/* 当前副作用在账号切换时读取账号级快捷回复,并在 cleanup 中取消旧请求。 */ () => {
|
||||
quickReplyControllerRef.current?.abort();
|
||||
// sequence 保存本次账号快捷回复请求代次。
|
||||
const sequence = ++quickReplySequenceRef.current;
|
||||
if (!activeAccountID) {
|
||||
setQuickReplies([]);
|
||||
setQuickReplyDraft('');
|
||||
return undefined;
|
||||
}
|
||||
setQuickReplies([]);
|
||||
setQuickReplyDraft('');
|
||||
// controller 保存本次快捷回复请求的取消控制器。
|
||||
const controller = new AbortController();
|
||||
quickReplyControllerRef.current = controller;
|
||||
void getChatQuickReplies(activeAccountID, { signal: controller.signal }).then(/* replies 保存当前账号查询返回的快捷回复列表。 */ replies => {
|
||||
if (!controller.signal.aborted && sequence === quickReplySequenceRef.current) setQuickReplies(replies);
|
||||
}).catch(/* loadError 保存快捷回复查询失败原因;中止请求不显示错误。 */ loadError => {
|
||||
if (!controller.signal.aborted && sequence === quickReplySequenceRef.current && !isChatAbortError(loadError)) setMetadataError(loadError instanceof Error ? loadError.message : '读取快捷回复失败');
|
||||
});
|
||||
return /* 当前 cleanup 取消账号切换后不再有效的快捷回复请求。 */ () => controller.abort();
|
||||
}, [activeAccountID]);
|
||||
|
||||
useEffect(/* 当前副作用在账号或买家切换时读取备注,并丢弃已失效会话的响应。 */ () => {
|
||||
noteControllerRef.current?.abort();
|
||||
// sequence 保存本次买家备注请求代次。
|
||||
const sequence = ++noteSequenceRef.current;
|
||||
// buyerID 保存当前选中会话的稳定买家标识;没有会话时不发起请求。
|
||||
const buyerID = selectedSession?.buyer_id || '';
|
||||
if (!activeAccountID || !buyerID) {
|
||||
setBuyerNote(null);
|
||||
setNoteLoading(false);
|
||||
setNoteDialogOpen(false);
|
||||
setNoteEditing(false);
|
||||
return undefined;
|
||||
}
|
||||
// controller 保存本次买家备注请求的取消控制器。
|
||||
const controller = new AbortController();
|
||||
noteControllerRef.current = controller;
|
||||
setNoteLoading(true);
|
||||
void getChatBuyerNote(activeAccountID, buyerID, { signal: controller.signal }).then(/* note 保存当前账号与买家组合的完整备注。 */ note => {
|
||||
if (!controller.signal.aborted && sequence === noteSequenceRef.current) {
|
||||
setBuyerNote(note);
|
||||
setNoteDraft(note.content);
|
||||
}
|
||||
}).catch(/* loadError 保存买家备注读取失败原因;中止请求不显示错误。 */ loadError => {
|
||||
if (!controller.signal.aborted && sequence === noteSequenceRef.current && !isChatAbortError(loadError)) setMetadataError(loadError instanceof Error ? loadError.message : '读取买家备注失败');
|
||||
}).finally(/* 当前回调在仍为最新请求时结束备注加载状态。 */ () => {
|
||||
if (!controller.signal.aborted && sequence === noteSequenceRef.current) setNoteLoading(false);
|
||||
});
|
||||
return /* 当前 cleanup 取消会话切换后不再有效的买家备注请求。 */ () => controller.abort();
|
||||
}, [activeAccountID, selectedSession?.buyer_id]);
|
||||
|
||||
useEffect(/* 当前副作用在 Hook 卸载时清理复制反馈计时器,避免卸载后写入 React 状态。 */ () => {
|
||||
/** cleanupCopyTimer 清理仍在运行的复制反馈计时器。 */
|
||||
const cleanupCopyTimer = (): void => {
|
||||
if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current);
|
||||
};
|
||||
return cleanupCopyTimer;
|
||||
}, []);
|
||||
|
||||
/** 新增当前账号的快捷回复,并在服务端成功后插入当前列表。 */
|
||||
const addQuickReply = useCallback(/* 当前回调提交底部快捷回复表单。 */ async (): Promise<void> => {
|
||||
// content 保存去除首尾空白后的待创建文本,内部换行保持原样。
|
||||
const content = quickReplyDraft.trim();
|
||||
if (!activeAccountID || !content || quickReplyBusy) return;
|
||||
setQuickReplyBusy(true);
|
||||
setMetadataError('');
|
||||
try {
|
||||
// reply 保存服务端创建并返回的快捷回复。
|
||||
const reply = await createChatQuickReply(activeAccountID, content);
|
||||
setQuickReplies(/* 当前回调将新建记录插入按最新优先排列的列表。 */ current => [reply, ...current]);
|
||||
setQuickReplyDraft('');
|
||||
} catch (/* createError 保存创建快捷回复失败原因。 */ createError) {
|
||||
if (!isChatAbortError(createError)) setMetadataError(createError instanceof Error ? createError.message : '添加快捷回复失败');
|
||||
} finally {
|
||||
setQuickReplyBusy(false);
|
||||
}
|
||||
}, [activeAccountID, quickReplyBusy, quickReplyDraft]);
|
||||
|
||||
/** requestQuickReplyDelete 打开快捷回复删除确认框。 */
|
||||
const requestQuickReplyDelete = useCallback(/* 当前回调记录用户请求删除的快捷回复。 */ (reply: ChatQuickReply): void => {
|
||||
setPendingDeleteQuickReply(reply);
|
||||
}, []);
|
||||
|
||||
/** cancelQuickReplyDelete 关闭删除确认框,不改变快捷回复列表。 */
|
||||
const cancelQuickReplyDelete = useCallback(/* 当前回调放弃当前待确认的快捷回复删除动作。 */ (): void => {
|
||||
setPendingDeleteQuickReply(null);
|
||||
}, []);
|
||||
|
||||
/** confirmQuickReplyDelete 删除用户已确认的快捷回复。 */
|
||||
const confirmQuickReplyDelete = useCallback(/* 当前回调提交删除确认框中的快捷回复删除操作。 */ async (): Promise<void> => {
|
||||
if (!activeAccountID || !pendingDeleteQuickReply || quickReplyBusy) return;
|
||||
// quickReplyID 保存确认删除的稳定快捷回复标识,避免异步请求读取会变的 state。
|
||||
const quickReplyID = pendingDeleteQuickReply.id;
|
||||
setQuickReplyBusy(true);
|
||||
setMetadataError('');
|
||||
try {
|
||||
await deleteChatQuickReply(activeAccountID, quickReplyID);
|
||||
setQuickReplies(/* 当前回调只移除服务端已成功删除的快捷回复。 */ current => current.filter(/* reply 保存当前参与删除匹配的快捷回复。 */ reply => reply.id !== quickReplyID));
|
||||
setPendingDeleteQuickReply(null);
|
||||
} catch (/* deleteError 保存删除快捷回复失败原因。 */ deleteError) {
|
||||
if (!isChatAbortError(deleteError)) setMetadataError(deleteError instanceof Error ? deleteError.message : '删除快捷回复失败');
|
||||
} finally {
|
||||
setQuickReplyBusy(false);
|
||||
}
|
||||
}, [activeAccountID, pendingDeleteQuickReply, quickReplyBusy]);
|
||||
|
||||
/** copyQuickReply 将快捷回复正文复制到系统剪贴板,并给出短暂成功反馈。 */
|
||||
const copyQuickReply = useCallback(/* 当前回调响应快捷回复复制按钮的用户操作。 */ async (reply: ChatQuickReply): Promise<void> => {
|
||||
if (!navigator.clipboard?.writeText) {
|
||||
setMetadataError('当前浏览器不支持复制到剪贴板');
|
||||
return;
|
||||
}
|
||||
setMetadataError('');
|
||||
try {
|
||||
await navigator.clipboard.writeText(reply.content);
|
||||
setCopiedQuickReplyID(reply.id);
|
||||
if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current);
|
||||
copyTimerRef.current = window.setTimeout(/* 当前回调在短暂反馈结束后清除复制成功状态。 */ () => setCopiedQuickReplyID(null), 1600);
|
||||
} catch (/* copyError 保存系统剪贴板拒绝写入时的失败原因。 */ copyError) {
|
||||
setMetadataError(copyError instanceof Error ? copyError.message : '复制快捷回复失败');
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** openNoteDialog 打开当前买家的完整备注,并默认进入只读查看状态。 */
|
||||
const openNoteDialog = useCallback(/* 当前回调响应聊天标题中的备注摘要点击。 */ (): void => {
|
||||
setNoteDraft(buyerNote?.content || '');
|
||||
setNoteEditing(false);
|
||||
setNoteDialogOpen(true);
|
||||
}, [buyerNote?.content]);
|
||||
|
||||
/** closeNoteDialog 关闭备注弹窗并恢复当前已保存备注,放弃未保存草稿。 */
|
||||
const closeNoteDialog = useCallback(/* 当前回调响应备注弹窗的关闭操作。 */ (): void => {
|
||||
setNoteDraft(buyerNote?.content || '');
|
||||
setNoteEditing(false);
|
||||
setNoteDialogOpen(false);
|
||||
}, [buyerNote?.content]);
|
||||
|
||||
/** beginNoteEditing 将当前备注弹窗切换为可编辑状态。 */
|
||||
const beginNoteEditing = useCallback(/* 当前回调响应备注弹窗中的编辑按钮。 */ (): void => {
|
||||
setNoteDraft(buyerNote?.content || '');
|
||||
setNoteEditing(true);
|
||||
}, [buyerNote?.content]);
|
||||
|
||||
/** saveBuyerNote 保存当前会话买家的备注,并在成功后回到只读查看状态。 */
|
||||
const saveBuyerNote = useCallback(/* 当前回调提交买家备注编辑表单。 */ async (): Promise<void> => {
|
||||
// buyerID 保存当前会话的稳定买家标识;会话切换后不允许把旧备注写到新买家。
|
||||
const buyerID = selectedSession?.buyer_id || '';
|
||||
if (!activeAccountID || !buyerID || noteSaving) return;
|
||||
setNoteSaving(true);
|
||||
setMetadataError('');
|
||||
try {
|
||||
// note 保存服务端标准化并持久化后的买家备注。
|
||||
const note = await saveChatBuyerNote(activeAccountID, buyerID, noteDraft);
|
||||
setBuyerNote(note);
|
||||
setNoteDraft(note.content);
|
||||
setNoteEditing(false);
|
||||
} catch (/* saveError 保存备注保存失败原因。 */ saveError) {
|
||||
if (!isChatAbortError(saveError)) setMetadataError(saveError instanceof Error ? saveError.message : '保存买家备注失败');
|
||||
} finally {
|
||||
setNoteSaving(false);
|
||||
}
|
||||
}, [activeAccountID, noteDraft, noteSaving, selectedSession?.buyer_id]);
|
||||
|
||||
/** clearMetadataError 清除快捷回复和备注区域最近展示的错误。 */
|
||||
const clearMetadataError = useCallback(/* 当前回调在用户继续编辑或关闭错误提示时清空旧错误。 */ (): void => {
|
||||
setMetadataError('');
|
||||
}, []);
|
||||
|
||||
return {
|
||||
quickReplies, quickReplyDraft, setQuickReplyDraft, quickReplyBusy,
|
||||
pendingDeleteQuickReply, requestQuickReplyDelete, cancelQuickReplyDelete, confirmQuickReplyDelete, addQuickReply,
|
||||
copyQuickReply, copiedQuickReplyID, buyerNote, noteLoading, noteDialogOpen, noteEditing, noteDraft, setNoteDraft,
|
||||
noteSaving, openNoteDialog, closeNoteDialog, beginNoteEditing, saveBuyerNote, metadataError, clearMetadataError,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountDetail {
|
||||
/** 闲鱼账号稳定标识。 */
|
||||
id: string;
|
||||
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
|
||||
cookie_configured?: boolean;
|
||||
/** 账号是否允许运行。 */
|
||||
enabled: boolean;
|
||||
/** 是否自动确认订单。 */
|
||||
auto_confirm: boolean;
|
||||
/** 用户为账号设置的备注。 */
|
||||
remark?: string;
|
||||
/** 自动回复暂停时长,单位为分钟。 */
|
||||
pause_duration?: number;
|
||||
/** 暂停结束时间的 Unix 秒。 */
|
||||
paused_until?: number;
|
||||
/** 当前是否处于暂停状态。 */
|
||||
paused?: boolean;
|
||||
// 登录信息
|
||||
/** 用于密码登录的闲鱼用户名。 */
|
||||
username?: string;
|
||||
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
|
||||
login_password_configured?: boolean;
|
||||
/** 是否在密码登录时显示浏览器。 */
|
||||
show_browser?: boolean;
|
||||
// Frontend helpers
|
||||
/** 平台账号昵称。 */
|
||||
nickname?: string;
|
||||
/** 平台账号头像地址。 */
|
||||
avatar_url?: string;
|
||||
/** 资料刷新失败时的说明。 */
|
||||
profile_error?: string;
|
||||
/** 当前账号运行状态。 */
|
||||
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
|
||||
/** 当前运行状态的用户可见说明。 */
|
||||
runtime_message?: string;
|
||||
/** 当前运行实例是否已连接。 */
|
||||
runtime_connected?: boolean;
|
||||
/** 运行状态快照的更新时间。 */
|
||||
runtime_updated_at?: string;
|
||||
// AI设置
|
||||
/** 是否启用账号 AI 回复。 */
|
||||
ai_enabled?: boolean;
|
||||
/** 允许的最大折扣比例。 */
|
||||
max_discount_percent?: number;
|
||||
/** 允许的最大折扣金额。 */
|
||||
max_discount_amount?: number;
|
||||
/** 允许的最大砍价轮次。 */
|
||||
max_bargain_rounds?: number;
|
||||
/** 账号自定义提示词。 */
|
||||
custom_prompts?: string;
|
||||
// 账号级计划任务
|
||||
/** 是否启用自动评价。 */
|
||||
auto_rate_enabled?: boolean;
|
||||
/** 自动评价使用的文案。 */
|
||||
rate_content?: string;
|
||||
/** 是否启用每日擦亮。 */
|
||||
auto_polish_enabled?: boolean;
|
||||
/** 每日擦亮执行时间。 */
|
||||
polish_time?: string;
|
||||
/** 最近一次自动评价扫描时间。 */
|
||||
last_rate_scan_at?: number;
|
||||
/** 最近一次擦亮日期。 */
|
||||
last_polish_date?: string;
|
||||
/** 最近一次擦亮时间。 */
|
||||
last_polish_at?: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 ChatSession UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ChatSession {
|
||||
/** 账号稳定标识。 */
|
||||
account_id: string;
|
||||
/** 会话稳定标识。 */
|
||||
chat_id: string;
|
||||
/** 买家平台标识。 */
|
||||
buyer_id: string;
|
||||
/** 买家昵称。 */
|
||||
buyer_name: string;
|
||||
/** 买家头像地址。 */
|
||||
buyer_avatar_url?: string;
|
||||
/** 会话关联商品标识。 */
|
||||
item_id?: string;
|
||||
/** 会话关联商品标题。 */
|
||||
item_title?: string;
|
||||
/** 会话关联商品主图的公开地址。 */
|
||||
item_image_url?: string;
|
||||
/** 最近一条消息内容。 */
|
||||
last_message: string;
|
||||
/** 最近一条消息的 Unix 秒时间戳。 */
|
||||
last_message_at: number;
|
||||
/** 未读消息数量。 */
|
||||
unread_count: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 ChatMessage UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ChatMessage {
|
||||
/** 消息数据库主键。 */
|
||||
id: number;
|
||||
/** 消息所属账号标识。 */
|
||||
account_id: string;
|
||||
/** 消息所属会话标识。 */
|
||||
chat_id: string;
|
||||
/** 平台消息去重键。 */
|
||||
message_key: string;
|
||||
/** 消息方向。 */
|
||||
direction: 'incoming' | 'outgoing';
|
||||
/** 发送者平台标识。 */
|
||||
sender_id: string;
|
||||
/** 发送者名称。 */
|
||||
sender_name: string;
|
||||
/** 消息类型;audio 表示需在浏览器解码的语音,system 表示平台通知或交易卡片。 */
|
||||
message_type: 'text' | 'image' | 'video' | 'audio' | 'system';
|
||||
/** 消息正文或媒体地址。 */
|
||||
content: string;
|
||||
/** 语音消息的秒级时长;非语音或平台未提供时省略。 */
|
||||
media_duration?: number;
|
||||
/** 消息发送状态。 */
|
||||
status: 'received' | 'sending' | 'sent' | 'failed';
|
||||
/** 平台已读状态;旧消息可能没有该字段。 */
|
||||
read_status?: number;
|
||||
/** 平台确认已读的 Unix 秒时间戳;未确认时省略。 */
|
||||
read_at?: number;
|
||||
/** 消息发送时间的 Unix 秒。 */
|
||||
sent_at: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的账号级快捷回复 UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ChatQuickReply {
|
||||
/** 快捷回复稳定标识,用于 React 列表和删除请求。 */
|
||||
id: number;
|
||||
/** 快捷回复所属的闲鱼账号标识。 */
|
||||
account_id: string;
|
||||
/** 用户点击发送时提交到当前会话的文本模板。 */
|
||||
content: string;
|
||||
/** 快捷回复创建的 Unix 秒时间戳。 */
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的买家备注 UI 模型;备注按账号与买家 ID 隔离。 */
|
||||
export interface ChatBuyerNote {
|
||||
/** 备注所属的闲鱼账号标识。 */
|
||||
account_id: string;
|
||||
/** 备注所属的稳定平台买家标识。 */
|
||||
buyer_id: string;
|
||||
/** 完整备注正文;空字符串表示尚未填写。 */
|
||||
content: string;
|
||||
/** 最近保存的 Unix 秒时间戳;空备注保持零值。 */
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import {
|
||||
AlertCircle,Check,CheckCheck,ImagePlus,Loader2,MessageCircleMore,RefreshCw,
|
||||
Search,Send,Smile,UserRound,Wifi,WifiOff,X,
|
||||
AlertCircle,Check,CheckCheck,ImagePlus,Loader2,MessageCircleMore,PanelRightClose,PanelRightOpen,
|
||||
RefreshCw,Search,Send,Smile,UserRound,Wifi,WifiOff,X,
|
||||
} from 'lucide-react';
|
||||
import React from 'react';
|
||||
import Lightbox from 'yet-another-react-lightbox';
|
||||
import 'yet-another-react-lightbox/styles.css';
|
||||
import { AudioMessage } from '../components/AudioMessage';
|
||||
import ChatMetadataFeature from '../components/ChatMetadataFeature';
|
||||
import { useChat } from '../hooks';
|
||||
import { unreadBadgeClassName,unreadBadgeLabel } from '../state';
|
||||
|
||||
@@ -16,10 +18,11 @@ const Chat: React.FC = () => {
|
||||
messages, search, unreadOnly, draft, loading, messagesLoading, olderLoading, hasOlder, contactsLoading,
|
||||
hasMoreContacts, emojiOpen, sending, error, liveState, pendingImage, scrollRef, imageInputRef, setActiveAccountID,
|
||||
setActiveChatID, setSearch, setUnreadOnly, setDraft, setEmojiOpen, reloadSessions, loadMoreContacts,
|
||||
loadOlderMessages, handleMessageScroll, handleSend, handleImage, handlePastedImages, confirmSendImage, closeImagePreview, retrySend, retryAvailable,
|
||||
loadOlderMessages, handleMessageScroll, handleSend, handleQuickReply, handleImage, handlePastedImages, confirmSendImage, closeImagePreview, retrySend, retryAvailable,
|
||||
unreadForAccount, emojiURL, xianyuEmojis, renderXianyuText, formatClock, messageTime,
|
||||
} = useChat();
|
||||
|
||||
|
||||
// imageMessages 保存当前会话中的图片消息,供灯箱按消息顺序浏览。
|
||||
const imageMessages = React.useMemo(/* 当前回调筛选当前会话中的图片消息。 */ () => messages.filter(/* 当前回调判断消息是否为图片类型。 */ message => message.message_type === 'image'), [messages]);
|
||||
// imageSlides 将聊天图片转换为灯箱组件所需的展示模型。
|
||||
@@ -30,6 +33,8 @@ const Chat: React.FC = () => {
|
||||
const openLightbox = React.useCallback(/* 当前回调定位并打开指定聊天图片。 */ (messageKey: string): void => {
|
||||
setLightboxIndex(imageMessages.findIndex(/* 当前回调匹配图片消息键。 */ item => item.message_key === messageKey));
|
||||
}, [imageMessages]);
|
||||
// quickReplyPanelOpen 保存右侧快捷回复抽屉的展开状态;页面卸载后恢复默认收起。
|
||||
const [quickReplyPanelOpen, setQuickReplyPanelOpen] = React.useState(false);
|
||||
|
||||
if (loading) return <div className="flex h-[calc(100vh-4rem)] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-sky-500" /></div>;
|
||||
|
||||
@@ -96,14 +101,13 @@ const Chat: React.FC = () => {
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
{filteredSessions.map(/* 当前回调处理集合中的单个元素。 */ session => (
|
||||
<button key={session.chat_id} type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setActiveChatID(session.chat_id)}
|
||||
className={`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${session.chat_id === activeChatID ? 'bg-white shadow-chat-active' : 'hover:bg-white/80'}`}>
|
||||
className={`flex w-full gap-3 border-b border-slate-100 p-3.5 text-left transition-colors ${session.chat_id === activeChatID ? 'bg-white shadow-chat-active' : 'hover:bg-white/80'}`}>
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500">
|
||||
{session.buyer_avatar_url ? <img src={session.buyer_avatar_url} alt="" className="h-full w-full object-cover" /> : <UserRound className="h-5 w-5" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-extrabold text-slate-900">{session.buyer_name || `用户 ${session.buyer_id}`}</span>
|
||||
<span className="ml-auto shrink-0 text-[10px] font-medium text-slate-400">{formatClock(session.last_message_at)}</span>
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<span className="truncate text-xs text-slate-500">{session.last_message || '暂无消息'}</span>
|
||||
@@ -111,6 +115,10 @@ const Chat: React.FC = () => {
|
||||
</div>
|
||||
{session.item_title && <div className="mt-1.5 truncate text-[10px] font-medium text-sky-700">商品 · {session.item_title}</div>}
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col items-end gap-1.5">
|
||||
<span className="text-[10px] font-medium text-slate-400">{formatClock(session.last_message_at)}</span>
|
||||
{session.item_image_url && <img src={session.item_image_url} alt="" className="h-9 w-11 rounded-[4px] border border-slate-200 object-cover" />}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
{filteredSessions.length === 0 && <div className="px-6 py-16 text-center text-sm text-slate-400">当前账号暂无匹配会话</div>}
|
||||
@@ -123,13 +131,13 @@ const Chat: React.FC = () => {
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle">
|
||||
<main className="relative flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle">
|
||||
{selectedSession ? (
|
||||
<>
|
||||
<div className="flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5">
|
||||
<div className="flex h-20 shrink-0 items-start border-b border-slate-200 bg-white px-5 pt-4">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-black text-slate-950">{selectedSession.buyer_name || selectedSession.buyer_id}</div>
|
||||
<div className="mt-0.5 truncate text-xs text-slate-500">用户 ID:{selectedSession.buyer_id}</div>
|
||||
<div className="mt-0.5 flex flex-col text-xs text-slate-500"><span>用户 ID:</span><span className="truncate">{selectedSession.buyer_id}</span></div>
|
||||
</div>
|
||||
<span className={`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${activeAccount?.runtime_state === 'online' ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500'}`}>
|
||||
{activeAccount?.runtime_state === 'online' ? '账号在线' : '账号离线'}
|
||||
@@ -171,6 +179,8 @@ const Chat: React.FC = () => {
|
||||
</button>
|
||||
) : message.message_type === 'video' ? (
|
||||
<video src={message.content} controls preload="metadata" className="max-h-80 max-w-full rounded-2xl bg-black" />
|
||||
) : message.message_type === 'audio' ? (
|
||||
<AudioMessage messageKey={message.message_key} src={message.content} outgoing={outgoing} initialDuration={message.media_duration} />
|
||||
) : (
|
||||
<div className={`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${outgoing ? 'rounded-br-md bg-sky-500 text-white' : 'rounded-bl-md border border-slate-200 bg-white text-slate-800'}`}>{renderXianyuText(message.content)}</div>
|
||||
)}
|
||||
@@ -201,6 +211,9 @@ const Chat: React.FC = () => {
|
||||
</div>
|
||||
<input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => void handleImage(event.target.files?.[0])} />
|
||||
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => imageInputRef.current?.click()} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="发送图片(最大 10MB)"><ImagePlus className="h-5 w-5" /></button>
|
||||
<button type="button" onClick={/* 当前回调依当前渲染状态切换右侧账号快捷回复抽屉,避免页面级外部点击监听与按钮切换相互抵消。 */ () => setQuickReplyPanelOpen(!quickReplyPanelOpen)} className="ml-auto rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600" title={quickReplyPanelOpen ? '收起快捷回复' : '展开快捷回复'} aria-label={quickReplyPanelOpen ? '收起快捷回复' : '展开快捷回复'}>
|
||||
{quickReplyPanelOpen ? <PanelRightClose className="h-5 w-5" /> : <PanelRightOpen className="h-5 w-5" />}
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100">
|
||||
<textarea value={draft} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setDraft(event.target.value)} rows={2} maxLength={2000}
|
||||
@@ -230,6 +243,7 @@ const Chat: React.FC = () => {
|
||||
<p className="mt-1 text-sm text-slate-400">该账号的新消息会实时出现在左侧列表。</p>
|
||||
</div>
|
||||
)}
|
||||
<ChatMetadataFeature activeAccountID={activeAccountID} selectedSession={selectedSession} quickReplyPanelOpen={quickReplyPanelOpen} closeQuickReplyPanel={/* 当前回调收起右侧快捷回复抽屉。 */ () => setQuickReplyPanelOpen(false)} sendQuickReply={handleQuickReply} sending={sending} accountOnline={activeAccount?.runtime_state === 'online'} />
|
||||
</main>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect,test } from 'vitest';
|
||||
import type { ChatMessage,ChatSession } from '../../../shared/api-contract/chat';
|
||||
import type { ChatMessage,ChatSession } from './api';
|
||||
import { collectChatReadReceipts,filterChatSessions,formatClock,isChatAbortError,isCurrentChatRequest,markOutgoingMessagesReadByIncoming,mergeLiveMessage,mergeOlderMessages,messageTime,unreadBadgeClassName,unreadBadgeLabel } from './state';
|
||||
|
||||
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
|
||||
|
||||
@@ -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 { ChatMessage } from '../../../shared/api-contract/chat';
|
||||
import type { ChatMessage } from './api';
|
||||
import { getAccountDetails,getChatSessionPage } from './api';
|
||||
import { publishChatUnreadStatus } from './liveEvents';
|
||||
import { formatChatNewMessageTitle,useChatTitleNotification,useChatTitleNotifier } from './titleNotification';
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { formatLocalDate } from '../../../dateRange';
|
||||
import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from '../../../shared/api-contract/admin';
|
||||
import { get,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/admin';
|
||||
import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from './models';
|
||||
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
export type * from './models';
|
||||
|
||||
/** 仪表盘订单明细接口转换后的分页结果。 */
|
||||
export interface ValidOrdersResult {
|
||||
@@ -23,12 +24,13 @@ const normalizeOrderStatus = (value: unknown): OrderStatus => {
|
||||
};
|
||||
|
||||
/** 读取仪表盘概览统计。 */
|
||||
export const getDashboardStats = async (options?: RequestControlOptions): Promise<DashboardStatsResponse> => get('/api/v1/analytics/dashboard', undefined, options);
|
||||
export const getDashboardStats = async (options?: RequestControlOptions): Promise<DashboardStatsResponse> =>
|
||||
runContractRequest(/* signal 是本次仪表盘统计请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/analytics/dashboard', { signal }), 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);
|
||||
const response = await runContractRequest(/* signal 控制仪表盘商品读取的取消和超时。 */ signal => contractClient.GET('/api/v1/items', { params: { query: { cookie_id: accountID } }, signal }), options) as unknown as Item[] | ItemListEnvelope;
|
||||
// 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 }));
|
||||
@@ -48,17 +50,23 @@ export const getOrderAnalytics = async (range: number | { /** 统计起始日期
|
||||
} else {
|
||||
dateRange = range;
|
||||
}
|
||||
return get('/api/v1/analytics/orders', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options);
|
||||
return runContractRequest(/* signal 是本次订单分析请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/analytics/orders', {
|
||||
params: { query: { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() } },
|
||||
signal,
|
||||
}), 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']);
|
||||
const response = await runContractRequest(/* signal 是本次有效订单查询请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/analytics/orders/valid', {
|
||||
params: { query: { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() } },
|
||||
signal,
|
||||
}), options);
|
||||
// page 是生成契约或历史 data/result 包装后的有效订单分页元数据。
|
||||
const page = objectFrom<Partial<ValidOrdersResponse>>(response as unknown, ['data', 'result']) || {};
|
||||
// rows 是当前分页或兼容包装中的有效订单 transport DTO。
|
||||
const rows = collectionFrom<ValidOrderResponse>(response as unknown, ['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 '../../../shared/api-contract/admin';
|
||||
import type { DashboardStats,Item,OrderAnalyticsResponse } from './api';
|
||||
import { getDashboardStats,getItems,getOrderAnalytics,getValidOrders } from './api';
|
||||
import type { UseDashboardOptions } from './hooks';
|
||||
import { useDashboard } from './hooks';
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 OrderStatus UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type OrderStatus =
|
||||
| 'processing'
|
||||
| 'pending_ship'
|
||||
| 'shipped'
|
||||
| 'completed'
|
||||
| 'cancelled'
|
||||
| 'refunding'
|
||||
| 'unknown';
|
||||
|
||||
/** 由当前 feature adapter 归一后的 Order UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface Order {
|
||||
/** 订单本地数据库主键。 */
|
||||
id: string;
|
||||
/** 平台订单标识。 */
|
||||
order_id: string;
|
||||
/** 订单所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 订单关联商品标识。 */
|
||||
item_id: string;
|
||||
/** 商品标题。 */
|
||||
item_title?: string;
|
||||
/** 商品图片地址。 */
|
||||
item_image?: string;
|
||||
/** 商品价格文本。 */
|
||||
item_price?: string;
|
||||
/** 买家平台标识。 */
|
||||
buyer_id: string;
|
||||
/** 购买数量。 */
|
||||
quantity: number;
|
||||
/** 订单金额文本。 */
|
||||
amount: string;
|
||||
/** 前端归一化后的订单状态。 */
|
||||
status: OrderStatus;
|
||||
/** 服务端原始订单状态。 */
|
||||
order_status?: OrderStatus;
|
||||
/** 收货人姓名。 */
|
||||
receiver_name?: string;
|
||||
/** 收货人电话。 */
|
||||
receiver_phone?: string;
|
||||
/** 收货地址。 */
|
||||
receiver_address?: string;
|
||||
/** 订单创建时间。 */
|
||||
created_at?: string;
|
||||
/** 订单更新时间。 */
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface Item {
|
||||
/** 本地商品数据库主键。 */
|
||||
id: string | number;
|
||||
/** 商品所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 平台商品标识。 */
|
||||
item_id: string;
|
||||
/** 商品标题。 */
|
||||
item_title?: string;
|
||||
/** 商品描述。 */
|
||||
item_description?: string;
|
||||
/** 商品价格文本。 */
|
||||
item_price?: string;
|
||||
/** 商品主图地址。 */
|
||||
item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes
|
||||
/** 商品分类标识。 */
|
||||
item_category?: string;
|
||||
/** 商品详情原始 JSON。 */
|
||||
item_detail?: string;
|
||||
/** 是否启用多规格。 */
|
||||
is_multi_spec?: number | boolean;
|
||||
/** 是否按数量发货。 */
|
||||
multi_quantity_delivery?: number | boolean;
|
||||
/** 是否启用多数量发货兼容字段。 */
|
||||
is_multi_qty_ship?: number | boolean;
|
||||
}
|
||||
|
||||
/** 仪表盘兼容历史 items 包装时使用的最小响应模型。 */
|
||||
export interface ItemListEnvelope {
|
||||
/** 历史包装中的商品数组。 */ items?: Item[];
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AdminStats UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AdminStats {
|
||||
/** 用户总数。 */
|
||||
total_users: number;
|
||||
/** 账号总数。 */
|
||||
total_cookies: number;
|
||||
/** 启用账号数。 */
|
||||
active_cookies: number;
|
||||
/** 卡券组总数。 */
|
||||
total_cards: number;
|
||||
/** 关键词规则总数。 */
|
||||
total_keywords: number;
|
||||
/** 订单总数。 */
|
||||
total_orders: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 DashboardStats UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface DashboardStats {
|
||||
/** 账号总数。 */
|
||||
total_cookies: number;
|
||||
/** 启用账号数。 */
|
||||
active_cookies: number;
|
||||
/** 卡券组总数。 */
|
||||
total_cards: number;
|
||||
/** 关键词规则总数。 */
|
||||
total_keywords: number;
|
||||
/** 订单总数。 */
|
||||
total_orders: number;
|
||||
/** 可用卡券库存量。 */
|
||||
available_card_stock: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 OrderAnalytics UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderAnalytics {
|
||||
/** 收入汇总。 */
|
||||
revenue_stats: {
|
||||
/** 总收入金额。 */
|
||||
total_amount: number;
|
||||
/** 总订单数。 */
|
||||
total_orders: number;
|
||||
};
|
||||
/** 按日期聚合的订单统计。 */
|
||||
daily_stats: Array<{
|
||||
/** 统计日期。 */
|
||||
date: string;
|
||||
/** 当日订单金额。 */
|
||||
amount: number;
|
||||
/** 当日订单数量。 */
|
||||
order_count: number;
|
||||
}>;
|
||||
/** 按商品聚合的订单统计。 */
|
||||
item_stats?: Array<{
|
||||
/** 商品标识。 */
|
||||
item_id: string;
|
||||
/** 商品订单数。 */
|
||||
order_count: number;
|
||||
/** 商品订单总金额。 */
|
||||
total_amount: number;
|
||||
/** 商品订单平均金额。 */
|
||||
avg_amount: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
/** 管理员全局统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AdminStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AdminStatsResponse extends AdminStats {}
|
||||
|
||||
/** 当前用户数据概览响应。 */
|
||||
/** 由当前 feature adapter 归一后的 DashboardStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface DashboardStatsResponse extends DashboardStats {}
|
||||
|
||||
/** 订单收益统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AnalyticsRevenueStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AnalyticsRevenueStatsResponse {
|
||||
/** 统计范围内的订单数。 */
|
||||
total_orders: number;
|
||||
/** 统计范围内的订单总金额。 */
|
||||
total_amount: number;
|
||||
/** 订单平均金额。 */
|
||||
avg_amount: number;
|
||||
/** 买家数量。 */
|
||||
unique_buyers: number;
|
||||
/** 商品数量。 */
|
||||
unique_items: number;
|
||||
}
|
||||
|
||||
/** 按日期聚合的订单统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AnalyticsDailyStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AnalyticsDailyStatsResponse {
|
||||
/** 用户本地日期。 */
|
||||
date: string;
|
||||
/** 当天订单数。 */
|
||||
order_count: number;
|
||||
/** 当天订单金额。 */
|
||||
amount: number;
|
||||
}
|
||||
|
||||
/** 按订单状态聚合的统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AnalyticsStatusStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AnalyticsStatusStatsResponse {
|
||||
/** 归一化后的订单状态。 */
|
||||
status: string;
|
||||
/** 该状态订单数。 */
|
||||
count: number;
|
||||
/** 该状态订单金额。 */
|
||||
amount: number;
|
||||
}
|
||||
|
||||
/** 按收货城市聚合的统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AnalyticsCityStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AnalyticsCityStatsResponse {
|
||||
/** 收货城市。 */
|
||||
city: string;
|
||||
/** 该城市订单数。 */
|
||||
order_count: number;
|
||||
/** 该城市订单金额。 */
|
||||
total_amount: number;
|
||||
}
|
||||
|
||||
/** 按商品聚合的统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AnalyticsItemStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AnalyticsItemStatsResponse {
|
||||
/** 商品平台标识。 */
|
||||
item_id: string;
|
||||
/** 该商品订单数。 */
|
||||
order_count: number;
|
||||
/** 该商品订单金额。 */
|
||||
total_amount: number;
|
||||
/** 该商品订单平均金额。 */
|
||||
avg_amount: number;
|
||||
}
|
||||
|
||||
/** 订单分析接口响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderAnalyticsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderAnalyticsResponse {
|
||||
/** 收益统计。 */
|
||||
revenue_stats: AnalyticsRevenueStatsResponse;
|
||||
/** 按日统计。 */
|
||||
daily_stats: AnalyticsDailyStatsResponse[];
|
||||
/** 按状态统计。 */
|
||||
status_stats: AnalyticsStatusStatsResponse[];
|
||||
/** 按城市统计。 */
|
||||
city_stats: AnalyticsCityStatsResponse[];
|
||||
/** 按商品统计。 */
|
||||
item_stats: AnalyticsItemStatsResponse[];
|
||||
}
|
||||
|
||||
/** 有效订单明细响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ValidOrderResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ValidOrderResponse {
|
||||
/** 平台订单标识。 */
|
||||
order_id: string;
|
||||
/** 商品平台标识。 */
|
||||
item_id: string;
|
||||
/** 买家平台标识。 */
|
||||
buyer_id: string;
|
||||
/** 商品标题。 */
|
||||
item_title: string;
|
||||
/** 商品图片地址。 */
|
||||
item_image: string;
|
||||
/** 订单数量文本。 */
|
||||
quantity: string;
|
||||
/** 订单金额文本。 */
|
||||
amount: string;
|
||||
/** 兼容保留的订单状态。 */
|
||||
order_status: string;
|
||||
/** 归一化后的订单状态。 */
|
||||
status: string;
|
||||
/** 订单所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 订单创建时间。 */
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** 有效订单分页响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ValidOrdersResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ValidOrdersResponse {
|
||||
/** 当前页有效订单。 */
|
||||
orders: ValidOrderResponse[];
|
||||
/** 符合条件的订单总数。 */
|
||||
total: number;
|
||||
/** 当前页码。 */
|
||||
page: number;
|
||||
/** 当前页大小。 */
|
||||
page_size: number;
|
||||
/** 是否还有未返回的订单。 */
|
||||
truncated: boolean;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect,test } from 'vitest';
|
||||
import type { OrderAnalytics } from '../../../shared/api-contract/admin';
|
||||
import type { OrderAnalytics } from './api';
|
||||
import { buildCategoryData,buildChartData,buildItemNameMap,buildProductSalesData,buildSourceData,getMaxProductSales,getRangeLabel,getTrendPercent,isCurrentDashboardRequest } from './state';
|
||||
|
||||
// analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PublishLocation } from '../../../shared/api-contract/items';
|
||||
import type { PublishLocation } from './models';
|
||||
import {
|
||||
AccountDetail,
|
||||
BatchCancelResponse,
|
||||
@@ -11,21 +11,22 @@ ItemPublishBatchResponse,
|
||||
ItemPublishResponse,ItemSyncResponse,
|
||||
OperationResponse,
|
||||
ShippingRule
|
||||
} from '../../../shared/api-contract/items';
|
||||
import { ApiError,del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
} from './models';
|
||||
import { ApiError, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { contractClient, contractMultipartBody, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { collectionFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/items';
|
||||
export type * from './models';
|
||||
import { getPublishLocations as queryPublishLocations,type PublishLocationRequestOptions } from './amapLocation';
|
||||
|
||||
/** 商品账号筛选器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => runContractRequest(/* signal 控制商品页账号摘要请求的取消和超时。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options);
|
||||
|
||||
/** 商品页面读取自动化发货规则的兼容列表。 */
|
||||
export const getShippingRules = async (options?: RequestControlOptions): Promise<ShippingRule[]> => get('/api/v1/automation-rules', undefined, options);
|
||||
export const getShippingRules = async (options?: RequestControlOptions): Promise<ShippingRule[]> => runContractRequest(/* signal 控制商品页规则读取请求的取消和超时。 */ signal => contractClient.GET('/api/v1/automation-rules', { signal }), options) as unknown as Promise<ShippingRule[]>;
|
||||
|
||||
// getPublishLocations 通过 feature API 边界读取地点,并把取消/超时控制传入地图服务。
|
||||
export const getPublishLocations = (longitude: number, latitude: number, options?: PublishLocationRequestOptions): Promise<PublishLocation[]> => queryPublishLocations(longitude, latitude, options);
|
||||
export type { PublishLocation } from '../../../shared/api-contract/items';
|
||||
export type { PublishLocation } from './models';
|
||||
|
||||
// itemErrorMessage 将统一 HTTP 错误码归一为商品 feature 可执行的用户提示。
|
||||
export const itemErrorMessage = (error: unknown, fallback: string): string => {
|
||||
@@ -59,7 +60,7 @@ const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
// 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);
|
||||
const res = await runContractRequest(/* signal 控制商品列表请求的取消和超时。 */ signal => contractClient.GET('/api/v1/items', { params: { query: { cookie_id: cookieId } }, signal }), options) as unknown;
|
||||
// items 商品列表,用于当前 API 处理流程。
|
||||
const items = collectionFrom<Item>(res, ['items', 'data', 'results']);
|
||||
return items.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
|
||||
@@ -73,17 +74,17 @@ export const getItems = async (cookieId?: string, options?: RequestControlOption
|
||||
|
||||
// syncItemsFromAccount 从账号同步商品。
|
||||
export const syncItemsFromAccount = async (cookieId: string): Promise<ItemSyncResponse> => {
|
||||
return post('/api/v1/items/get-all-from-account', { cookie_id: cookieId });
|
||||
return runContractRequest(/* signal 控制商品同步请求的取消和超时。 */ signal => contractClient.POST('/api/v1/items/get-all-from-account', { body: { cookie_id: cookieId } as never, signal })) as unknown as Promise<ItemSyncResponse>;
|
||||
}
|
||||
|
||||
// deleteItem 删除商品。
|
||||
export const deleteItem = async (cookieId: string, itemId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/items/${cookieId}/${itemId}`);
|
||||
return runContractRequest(/* signal 控制商品删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: cookieId, item_id: itemId } }, signal }));
|
||||
}
|
||||
|
||||
// createItem 创建商品。
|
||||
export const createItem = async (cookieId: string, data: Partial<Item>): Promise<OperationResponse> => {
|
||||
return post(`/api/v1/items/${cookieId}`, data);
|
||||
return runContractRequest(/* signal 控制商品创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/items/{cookie_id}', { params: { path: { cookie_id: cookieId } }, body: data as never, signal }));
|
||||
}
|
||||
|
||||
// publishItem 发布商品。
|
||||
@@ -114,7 +115,7 @@ export const publishItem = async (form: {
|
||||
file of form.images) {
|
||||
body.append('images', file);
|
||||
}
|
||||
return postForm('/api/v1/items/publish', body);
|
||||
return runContractRequest(/* signal 控制商品发布上传请求的取消和超时。 */ signal => contractClient.POST('/api/v1/items/publish', { body: contractMultipartBody(body), signal })) as unknown as Promise<ItemPublishResponse>;
|
||||
}
|
||||
|
||||
// recommendPublishCategory 推荐商品发布分类。
|
||||
@@ -127,7 +128,7 @@ export const recommendPublishCategory = async (cookieId: string, keyword: string
|
||||
// 该类型收口不改变凭证刷新和错误处理。
|
||||
// 前端批量发布流程可直接复用 category。
|
||||
// 旧路径继续由现有 Vite 代理转发。
|
||||
return post('/api/v1/items/publish-categories/recommend', { cookie_id: cookieId, keyword }, options);
|
||||
return runContractRequest(/* signal 控制商品类目推荐请求的取消和超时。 */ signal => contractClient.POST('/api/v1/items/publish-categories/recommend', { body: { cookie_id: cookieId, keyword } as never, signal }), options) as unknown as Promise<CategoryRecommendationResponse>;
|
||||
};
|
||||
|
||||
// previewItemPublishBatch 预览商品批量发布。
|
||||
@@ -156,45 +157,49 @@ export const previewItemPublishBatch = async (form: {
|
||||
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
body.set('publish_interval_seconds', String(form.publishIntervalSeconds ?? 5));
|
||||
return postForm('/api/v1/items/publish-batches/preview', body, options);
|
||||
return runContractRequest(/* signal 控制批量发布预览上传的取消和超时。 */ signal => contractClient.POST('/api/v1/items/publish-batches/preview', { body: contractMultipartBody(body), signal }), options) as unknown as Promise<ItemPublishBatchPreviewResponse>;
|
||||
}
|
||||
|
||||
// startItemPublishBatch 启动商品批量发布。
|
||||
export const startItemPublishBatch = async (previewId: string, options?: RequestControlOptions): Promise<BatchIDResponse> => {
|
||||
return post('/api/v1/items/publish-batches', { preview_id: previewId }, options);
|
||||
return runContractRequest(/* signal 控制批量发布启动请求的取消和超时。 */ signal => contractClient.POST('/api/v1/items/publish-batches', { body: { preview_id: previewId } as never, signal }), options) as unknown as Promise<BatchIDResponse>;
|
||||
}
|
||||
|
||||
// getItemPublishBatch 读取商品发布批次。
|
||||
export const getItemPublishBatch = async (batchId: string, options?: RequestControlOptions): Promise<ItemPublishBatchResponse> => {
|
||||
return get(`/api/v1/items/publish-batches/${batchId}`, undefined, options);
|
||||
return runContractRequest(/* signal 控制批量发布状态读取的取消和超时。 */ signal => contractClient.GET('/api/v1/items/publish-batches/{batch_id}', { params: { path: { batch_id: batchId } }, signal }), options) as unknown as Promise<ItemPublishBatchResponse>;
|
||||
}
|
||||
|
||||
// getItemPublishBatches 读取商品发布批次列表。
|
||||
export const getItemPublishBatches = async (limit = 20, options?: RequestControlOptions): Promise<ItemPublishBatchResponse[]> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const res = await get<unknown>('/api/v1/items/publish-batches', { limit }, options);
|
||||
const res = await runContractRequest(/* signal 控制批量发布列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/items/publish-batches', { params: { query: { limit } }, signal }), options) as unknown;
|
||||
return collectionFrom<ItemPublishBatchResponse>(res, ['batches', 'data', 'items']);
|
||||
}
|
||||
|
||||
// deleteItemPublishBatch 删除商品发布批次。
|
||||
export const deleteItemPublishBatch = async (batchId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/items/publish-batches/${batchId}`, undefined, options);
|
||||
return runContractRequest(/* signal 控制批量发布删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/items/publish-batches/{batch_id}', { params: { path: { batch_id: batchId } }, signal }), options);
|
||||
}
|
||||
|
||||
// cancelItemPublishBatch 取消商品发布批次。
|
||||
export const cancelItemPublishBatch = async (batchId: string, options?: RequestControlOptions): Promise<BatchCancelResponse> => {
|
||||
return post(`/api/v1/items/publish-batches/${batchId}/cancel`, {}, options);
|
||||
return runContractRequest(/* signal 控制批量发布取消请求的取消和超时。 */ signal => contractClient.POST('/api/v1/items/publish-batches/{batch_id}/cancel', { params: { path: { batch_id: batchId } }, body: {} as never, signal }), options) as unknown as Promise<BatchCancelResponse>;
|
||||
}
|
||||
|
||||
// retryFailedItemPublishBatch 重试失败的商品发布任务。
|
||||
export const retryFailedItemPublishBatch = async (batchId: string, options?: RequestControlOptions): Promise<BatchIDResponse> => {
|
||||
return post(`/api/v1/items/publish-batches/${batchId}/retry-failed`, {}, options);
|
||||
return runContractRequest(/* signal 控制批量发布重试请求的取消和超时。 */ signal => contractClient.POST('/api/v1/items/publish-batches/{batch_id}/retry-failed', { params: { path: { batch_id: batchId } }, body: {} as never, signal }), options) as unknown as Promise<BatchIDResponse>;
|
||||
}
|
||||
|
||||
// updateItem 更新商品。
|
||||
export const updateItem = async (cookieId: string, itemId: string, data: Partial<Item>): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/items/${cookieId}/${itemId}`, data);
|
||||
return runContractRequest(/* signal 控制商品更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: cookieId, item_id: itemId } }, body: data as never, signal }));
|
||||
}
|
||||
|
||||
/** 读取指定账号与商品的详情,用于编辑器恢复表单。 */
|
||||
export const getItemDetail = async (accountID: string, itemID: string): Promise<ItemDetailResponse> => get(`/api/v1/items/${accountID}/${itemID}`);
|
||||
/** 读取指定账号与商品的详情,用于编辑器恢复表单,并将生成传输 DTO 保持在 feature adapter 边界。 */
|
||||
export const getItemDetail = async (accountID: string, itemID: string): Promise<ItemDetailResponse> => {
|
||||
// response 保存已由 OpenAPI 路径类型约束的商品详情传输响应。
|
||||
const response = await runContractRequest(/* signal 控制商品详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: accountID, item_id: itemID } }, signal }));
|
||||
return response;
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
// @vitest-environment jsdom
|
||||
// 本测试需要浏览器文件控件与 File API,因此固定使用 jsdom 环境。
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import { consumeSelectedFile } from './fileInput';
|
||||
|
||||
// ItemList 文件选择测试覆盖同一路径的表格在保存后能够被重新读取。
|
||||
describe('consumeSelectedFile',
|
||||
// 测试组回调验证读取文件后重置原生 input 的浏览器兼容行为。
|
||||
() => {
|
||||
// 连续两次选择同名文件时,每次都返回对应 File 快照并清空上一轮原生选择值。
|
||||
test('clears the native input after each selected file',
|
||||
// 测试回调模拟浏览器在用户重新选择同一路径前写入的文件列表和伪路径值。
|
||||
() => {
|
||||
// input 保存可被测试替换 files 与 value 行为的文件控件。
|
||||
const input = document.createElement('input');
|
||||
// currentValue 保存浏览器文件控件的当前伪路径值,空值代表下次同一路径选择会重新触发 change。
|
||||
let currentValue = 'C:\\fakepath\\products.xlsx';
|
||||
Object.defineProperty(input, 'value', {
|
||||
configurable: true,
|
||||
get: /* 当前访问器返回模拟的文件控件伪路径。 */ () => currentValue,
|
||||
set: /* 当前访问器记录业务代码清空原生控件的操作。 */ value => { currentValue = String(value); },
|
||||
});
|
||||
// firstFile 保存首次选择时浏览器创建的文件快照。
|
||||
const firstFile = new File(['old-content'], 'products.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
Object.defineProperty(input, 'files', { configurable: true, value: [firstFile] as unknown as FileList });
|
||||
expect(consumeSelectedFile(input)).toBe(firstFile);
|
||||
expect(currentValue).toBe('');
|
||||
|
||||
// secondFile 保存同名文件修改后再次选择时浏览器创建的新快照。
|
||||
const secondFile = new File(['new-content'], 'products.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
currentValue = 'C:\\fakepath\\products.xlsx';
|
||||
Object.defineProperty(input, 'files', { configurable: true, value: [secondFile] as unknown as FileList });
|
||||
expect(consumeSelectedFile(input)).toBe(secondFile);
|
||||
expect(currentValue).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* consumeSelectedFile 读取文件控件当前选择的首个文件,并立即重置原生值。
|
||||
* input 是批量铺货表格控件;返回值是可由 React 状态持有的文件快照,重置让用户可再次选择相同路径的已修改文件。
|
||||
*/
|
||||
export const consumeSelectedFile = (input: HTMLInputElement): File | null => {
|
||||
// selectedFile 保存本次 change 事件携带的文件快照;无选择或用户取消时为 null。
|
||||
const selectedFile = input.files?.[0] || null;
|
||||
// 原生控件必须在读取后清空,否则浏览器可能将相同路径的再次选择视为未变化而不触发 change。
|
||||
input.value = '';
|
||||
return selectedFile;
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from '../../../shared/api-contract/items';
|
||||
import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from './api';
|
||||
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 '../../../shared/api-contract/items';
|
||||
import type { Item } from './api';
|
||||
import { createItem,deleteItem,getPublishLocations,publishItem,syncItemsFromAccount,updateItem } from './api';
|
||||
import { useItemActions,type ItemActionsOptions } from './itemActions';
|
||||
|
||||
|
||||
@@ -0,0 +1,457 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 PublishLocation UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface PublishLocation {
|
||||
/** 行政区划展示名称。 */
|
||||
area: string;
|
||||
/** 城市展示名称。 */
|
||||
city: string;
|
||||
/** 平台使用的行政区划标识。 */
|
||||
division_id: string;
|
||||
/** 地点经度。 */
|
||||
longitude: number;
|
||||
/** 地点纬度。 */
|
||||
latitude: number;
|
||||
/** 平台兴趣点标识。 */
|
||||
poi_id: string;
|
||||
/** 平台兴趣点展示名称。 */
|
||||
poi_name: string;
|
||||
/** 省份展示名称。 */
|
||||
province: string;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountDetail {
|
||||
/** 闲鱼账号稳定标识。 */
|
||||
id: string;
|
||||
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
|
||||
cookie_configured?: boolean;
|
||||
/** 账号是否允许运行。 */
|
||||
enabled: boolean;
|
||||
/** 是否自动确认订单。 */
|
||||
auto_confirm: boolean;
|
||||
/** 用户为账号设置的备注。 */
|
||||
remark?: string;
|
||||
/** 自动回复暂停时长,单位为分钟。 */
|
||||
pause_duration?: number;
|
||||
/** 暂停结束时间的 Unix 秒。 */
|
||||
paused_until?: number;
|
||||
/** 当前是否处于暂停状态。 */
|
||||
paused?: boolean;
|
||||
// 登录信息
|
||||
/** 用于密码登录的闲鱼用户名。 */
|
||||
username?: string;
|
||||
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
|
||||
login_password_configured?: boolean;
|
||||
/** 是否在密码登录时显示浏览器。 */
|
||||
show_browser?: boolean;
|
||||
// Frontend helpers
|
||||
/** 平台账号昵称。 */
|
||||
nickname?: string;
|
||||
/** 平台账号头像地址。 */
|
||||
avatar_url?: string;
|
||||
/** 资料刷新失败时的说明。 */
|
||||
profile_error?: string;
|
||||
/** 当前账号运行状态。 */
|
||||
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
|
||||
/** 当前运行状态的用户可见说明。 */
|
||||
runtime_message?: string;
|
||||
/** 当前运行实例是否已连接。 */
|
||||
runtime_connected?: boolean;
|
||||
/** 运行状态快照的更新时间。 */
|
||||
runtime_updated_at?: string;
|
||||
// AI设置
|
||||
/** 是否启用账号 AI 回复。 */
|
||||
ai_enabled?: boolean;
|
||||
/** 允许的最大折扣比例。 */
|
||||
max_discount_percent?: number;
|
||||
/** 允许的最大折扣金额。 */
|
||||
max_discount_amount?: number;
|
||||
/** 允许的最大砍价轮次。 */
|
||||
max_bargain_rounds?: number;
|
||||
/** 账号自定义提示词。 */
|
||||
custom_prompts?: string;
|
||||
// 账号级计划任务
|
||||
/** 是否启用自动评价。 */
|
||||
auto_rate_enabled?: boolean;
|
||||
/** 自动评价使用的文案。 */
|
||||
rate_content?: string;
|
||||
/** 是否启用每日擦亮。 */
|
||||
auto_polish_enabled?: boolean;
|
||||
/** 每日擦亮执行时间。 */
|
||||
polish_time?: string;
|
||||
/** 最近一次自动评价扫描时间。 */
|
||||
last_rate_scan_at?: number;
|
||||
/** 最近一次擦亮日期。 */
|
||||
last_polish_date?: string;
|
||||
/** 最近一次擦亮时间。 */
|
||||
last_polish_at?: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface Item {
|
||||
/** 本地商品数据库主键。 */
|
||||
id: string | number;
|
||||
/** 商品所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 平台商品标识。 */
|
||||
item_id: string;
|
||||
/** 商品标题。 */
|
||||
item_title?: string;
|
||||
/** 商品描述。 */
|
||||
item_description?: string;
|
||||
/** 商品价格文本。 */
|
||||
item_price?: string;
|
||||
/** 商品主图地址。 */
|
||||
item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes
|
||||
/** 商品分类标识。 */
|
||||
item_category?: string;
|
||||
/** 商品详情原始 JSON。 */
|
||||
item_detail?: string;
|
||||
/** 是否启用多规格。 */
|
||||
is_multi_spec?: number | boolean;
|
||||
/** 是否按数量发货。 */
|
||||
multi_quantity_delivery?: number | boolean;
|
||||
/** 是否启用多数量发货兼容字段。 */
|
||||
is_multi_qty_ship?: number | boolean;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AutomationTriggerType UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout';
|
||||
/** 由当前 feature adapter 归一后的 AutomationActionType UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type AutomationActionType = 'confirm_shipment' | 'send_card' | 'send_text';
|
||||
|
||||
// Rules
|
||||
/** 由当前 feature adapter 归一后的 ShippingRule UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ShippingRule {
|
||||
/** 规则标识。 */
|
||||
id: string;
|
||||
/** 规则名称。 */
|
||||
name: string;
|
||||
/** 规则触发类型。 */
|
||||
trigger_type: AutomationTriggerType;
|
||||
/** 规则匹配关键词。 */
|
||||
item_keyword: string; // Legacy UI helper
|
||||
/** 规则限定的账号标识。 */
|
||||
cookie_id?: string;
|
||||
/** 规则限定的商品标识。 */
|
||||
item_id?: string;
|
||||
/** 规则限定的商品标题。 */
|
||||
item_title?: string;
|
||||
/** 首个发卡动作使用的卡券组 ID。 */
|
||||
card_group_id: number; // First send_card action card id
|
||||
/** 首个发卡动作使用的卡券组名称。 */
|
||||
card_group_name?: string; // UI helper
|
||||
/** 规则优先级。 */
|
||||
priority: number;
|
||||
/** 规则是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 规则原始配置 JSON。 */
|
||||
config_json?: string;
|
||||
/** 规则动作列表。 */
|
||||
actions: AutomationAction[];
|
||||
/** 规则规格变体列表。 */
|
||||
variants: ShippingVariant[];
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AutomationAction UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AutomationAction {
|
||||
/** 动作标识。 */
|
||||
id?: string;
|
||||
/** 动作类型。 */
|
||||
action_type: AutomationActionType;
|
||||
/** 动作使用的卡券组 ID。 */
|
||||
card_id?: number;
|
||||
/** 动作使用的卡券组名称。 */
|
||||
card_name?: string;
|
||||
/** 本次发放数量。 */
|
||||
delivery_count?: number;
|
||||
/** 文本消息模板。 */
|
||||
message_template?: string;
|
||||
/** 动作延迟秒数。 */
|
||||
delay_seconds?: number;
|
||||
/** 动作原始配置 JSON。 */
|
||||
config_json?: string;
|
||||
/** 动作是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 动作排序序号。 */
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 ShippingVariant UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ShippingVariant {
|
||||
/** 规格变体标识。 */
|
||||
id?: string;
|
||||
/** 规格名称。 */
|
||||
spec_name: string;
|
||||
/** 规格值。 */
|
||||
spec_value: string;
|
||||
/** 变体使用的卡券组 ID。 */
|
||||
card_id: number;
|
||||
/** 变体使用的卡券组名称。 */
|
||||
card_name?: string;
|
||||
/** 卡券类型。 */
|
||||
card_type?: 'api' | 'text' | 'data' | 'image';
|
||||
/** 变体发放数量。 */
|
||||
delivery_count: number;
|
||||
/** 变体是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 是否覆盖动作级延迟。 */
|
||||
delay_override?: boolean;
|
||||
/** 变体延迟秒数。 */
|
||||
delay_seconds?: number;
|
||||
/** 变体原始配置 JSON。 */
|
||||
config_json?: string;
|
||||
}
|
||||
|
||||
/** 单个本地商品详情接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemDetailResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemDetailResponse {
|
||||
/** 商品所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 平台商品标识。 */
|
||||
item_id: string;
|
||||
/** 商品标题。 */
|
||||
item_title: string;
|
||||
/** 商品描述。 */
|
||||
item_description: string;
|
||||
/** 商品分类标识。 */
|
||||
item_category: string;
|
||||
/** 商品价格文本。 */
|
||||
item_price: string;
|
||||
/** 商品详情原始 JSON。 */
|
||||
item_detail: string;
|
||||
/** 是否有多规格。 */
|
||||
is_multi_spec: boolean;
|
||||
/** 是否按数量发货。 */
|
||||
multi_quantity_delivery: boolean;
|
||||
}
|
||||
|
||||
/** 商品发布接口的具名成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemPublishResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemPublishResponse {
|
||||
/** 表示商品是否发布成功。 */
|
||||
success: boolean;
|
||||
/** 发布结果说明。 */
|
||||
message: string;
|
||||
/** 新商品的平台标识。 */
|
||||
item_id: string;
|
||||
/** 新商品的平台详情地址。 */
|
||||
item_url: string;
|
||||
/** 新商品主图地址。 */
|
||||
item_image: string;
|
||||
/** 新商品标题。 */
|
||||
item_title: string;
|
||||
/** 新商品价格文本。 */
|
||||
item_price: string;
|
||||
/** 新商品库存数量。 */
|
||||
quantity: number;
|
||||
/** 新商品分类标识。 */
|
||||
category_id: string;
|
||||
/** 新商品分类名称。 */
|
||||
category_name: string;
|
||||
}
|
||||
|
||||
/** 商品全集同步接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemSyncResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemSyncResponse {
|
||||
/** 表示同步是否完成。 */
|
||||
success: boolean;
|
||||
/** 同步结果说明。 */
|
||||
message: string;
|
||||
/** 平台返回的商品总数。 */
|
||||
total_count: number;
|
||||
/** 平台商品总页数。 */
|
||||
total_pages: number;
|
||||
/** 本地保存的商品数量。 */
|
||||
saved_count: number;
|
||||
/** 本地删除标记的商品数量。 */
|
||||
deleted_count: number;
|
||||
}
|
||||
|
||||
/** 商品分页同步接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemPageSyncResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemPageSyncResponse {
|
||||
/** 表示同步是否完成。 */
|
||||
success: boolean;
|
||||
/** 同步结果说明。 */
|
||||
message: string;
|
||||
/** 当前同步页码。 */
|
||||
page_number: number;
|
||||
/** 当前同步页大小。 */
|
||||
page_size: number;
|
||||
/** 当前页商品数量。 */
|
||||
current_count: number;
|
||||
/** 本地保存的商品数量。 */
|
||||
saved_count: number;
|
||||
}
|
||||
|
||||
/** 商品类目推荐接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 CategoryRecommendationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface CategoryRecommendationResponse {
|
||||
/** 类目推荐是否成功。 */
|
||||
success: boolean;
|
||||
/** 推荐商品类目。 */
|
||||
category: {
|
||||
/** 平台类目主键。 */
|
||||
cat_id: string;
|
||||
/** 平台类目名称。 */
|
||||
cat_name: string;
|
||||
/** 频道类目主键。 */
|
||||
channel_cat_id: string;
|
||||
/** 淘宝类目主键。 */
|
||||
tb_cat_id?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/** 商品批量发布预检逐行结果。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemPublishBatchPreviewRow UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemPublishBatchPreviewRow {
|
||||
/** 上传表格行号。 */
|
||||
row_no: number;
|
||||
/** 当前行是否通过预检。 */
|
||||
valid: boolean;
|
||||
/** 当前行校验错误列表。 */
|
||||
errors?: string[];
|
||||
/** 发布目标账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 商品标题。 */
|
||||
title: string;
|
||||
/** 商品价格文本。 */
|
||||
price: string;
|
||||
/** 商品库存数量。 */
|
||||
quantity: number;
|
||||
/** 商品图片引用列表。 */
|
||||
images: string[];
|
||||
/** 商品发布类目。 */
|
||||
category: CategoryRecommendationResponse['category'];
|
||||
/** 发布后自动化配置。 */
|
||||
automation?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 商品批量发布预检响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemPublishBatchPreviewResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemPublishBatchPreviewResponse {
|
||||
/** 预检流程是否完成。 */
|
||||
success: boolean;
|
||||
/** 后续启动发布使用的预检批次标识。 */
|
||||
preview_id: string;
|
||||
/** 预检总行数。 */
|
||||
total: number;
|
||||
/** 通过预检行数。 */
|
||||
valid: number;
|
||||
/** 未通过预检行数。 */
|
||||
invalid: number;
|
||||
/** 逐行预检结果。 */
|
||||
rows: ItemPublishBatchPreviewRow[];
|
||||
}
|
||||
|
||||
/** 商品批量发布任务启动或重试响应。 */
|
||||
/** 由当前 feature adapter 归一后的 BatchIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface BatchIDResponse {
|
||||
/** 任务操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 商品批量任务标识。 */
|
||||
batch_id: string;
|
||||
}
|
||||
|
||||
/** 商品批量发布任务取消响应。 */
|
||||
/** 由当前 feature adapter 归一后的 BatchCancelResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface BatchCancelResponse {
|
||||
/** 取消请求是否完成。 */
|
||||
success: boolean;
|
||||
/** 取消后的任务状态。 */
|
||||
status: string;
|
||||
}
|
||||
|
||||
/** 商品批量发布任务逐行详情。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemPublishBatchRowResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemPublishBatchRowResponse {
|
||||
/** 明细行主键。 */
|
||||
id: number;
|
||||
/** 导入表格行号。 */
|
||||
row_no: number;
|
||||
/** 发布目标账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 商品标题。 */
|
||||
title: string;
|
||||
/** 商品价格文本。 */
|
||||
price: string;
|
||||
/** 商品库存数量。 */
|
||||
quantity: number;
|
||||
/** 商品图片引用列表。 */
|
||||
images: string[];
|
||||
/** 商品发布类目。 */
|
||||
category: CategoryRecommendationResponse['category'];
|
||||
/** 发布后自动化配置。 */
|
||||
automation: Record<string, unknown>;
|
||||
/** 明细行状态。 */
|
||||
status: string;
|
||||
/** 发布成功后的平台商品标识。 */
|
||||
item_id: string;
|
||||
/** 发布成功后的商品地址。 */
|
||||
item_url: string;
|
||||
/** 明细行失败原因。 */
|
||||
error_message: string;
|
||||
/** 明细行失败类型。 */
|
||||
failure_kind: string;
|
||||
}
|
||||
|
||||
/** 商品批量发布任务详情响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemPublishBatchResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemPublishBatchResponse {
|
||||
/** 批量任务标识。 */
|
||||
id: string;
|
||||
/** 批量任务状态。 */
|
||||
status: string;
|
||||
/** 原始上传文件名。 */
|
||||
filename: string;
|
||||
/** 明细行总数。 */
|
||||
total: number;
|
||||
/** 成功发布数量。 */
|
||||
success: number;
|
||||
/** 失败数量。 */
|
||||
failed: number;
|
||||
/** 待处理数量。 */
|
||||
pending: number;
|
||||
/** 运行中数量。 */
|
||||
running: number;
|
||||
/** 可重试数量。 */
|
||||
retryable: number;
|
||||
/** 明细行结果。 */
|
||||
rows: ItemPublishBatchRowResponse[];
|
||||
/** 批次统一发货地。 */
|
||||
location?: Record<string, unknown>;
|
||||
/** 最终商品发布之间的最小间隔秒数。 */
|
||||
publish_interval_seconds?: number;
|
||||
/** 创建时间。 */
|
||||
created_at: string;
|
||||
/** 更新时间。 */
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** 商品批量发布任务列表响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemPublishBatchListResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemPublishBatchListResponse {
|
||||
/** 当前用户的批量任务列表。 */
|
||||
batches: ItemPublishBatchResponse[];
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
@@ -10,6 +10,7 @@ getShippingRules,
|
||||
} from '../api';
|
||||
import { batchStatusClass,batchStatusText } from '../batchState';
|
||||
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
|
||||
import { consumeSelectedFile } from '../fileInput';
|
||||
import { useItemPublishBatch } from '../hooks';
|
||||
import { useItemActions } from '../itemActions';
|
||||
import type { ItemListProps } from '../types';
|
||||
@@ -676,7 +677,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
className="hidden"
|
||||
type="file"
|
||||
accept=".xlsx,.csv,.tsv"
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchFile(e.target.files?.[0] || null)}
|
||||
onChange={/* 当前回调读取本次文件快照并重置原生控件,以便同一路径文件修改后可再次选择。 */ event => setBatchFile(consumeSelectedFile(event.currentTarget))}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors">
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from '../../../shared/api-contract/notifications';
|
||||
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
export type * from '../../../shared/api-contract/notifications';
|
||||
import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from './models';
|
||||
import { normalizeSystemSettingsUpdate } from '../../../shared/api-contract/settings';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
|
||||
export type * from './models';
|
||||
|
||||
/** 通知渠道写入时使用的具名请求 DTO。 */
|
||||
export interface NotificationChannelRequest {
|
||||
@@ -39,48 +41,43 @@ const stringifyNotificationEventTypes = (eventTypes?: NotificationEventType[]):
|
||||
|
||||
/** 把后端渠道 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 {
|
||||
// 历史损坏配置不阻止用户继续编辑渠道。
|
||||
}
|
||||
// config 是列表摘要不返回 SMTP 等秘密时使用的空编辑初始值。
|
||||
const config: Record<string, unknown> = {};
|
||||
// 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 };
|
||||
return { id: String(channel.id), name: channel.name, type, config, event_types: parseNotificationEventTypes(channel.event_types), enabled: channel.enabled };
|
||||
};
|
||||
|
||||
/** 获取全部通知渠道并转换为编辑器模型。 */
|
||||
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) };
|
||||
const response = await runContractRequest(/* signal 控制通知渠道列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/channels', { signal }), options);
|
||||
return { success: true, data: response.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 createNotificationChannel = async (data: Required<Pick<NotificationChannelRequest, 'name' | 'type' | 'config'>> & NotificationChannelRequest, options?: RequestControlOptions): Promise<MutationIDResponse> => runContractRequest(/* signal 控制通知渠道创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels', { body: { name: data.name, type: data.type, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types), enabled: data.enabled }, signal }), 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);
|
||||
const payload = {
|
||||
name: data.name,
|
||||
type: data.type,
|
||||
config: data.config === undefined ? undefined : JSON.stringify(data.config),
|
||||
event_types: data.event_types === undefined ? undefined : stringifyNotificationEventTypes(data.event_types),
|
||||
enabled: data.enabled,
|
||||
};
|
||||
return runContractRequest(/* signal 控制通知渠道更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/notifications/channels/{channel_id}', { params: { path: { channel_id: channelID } }, body: payload, signal }), options);
|
||||
};
|
||||
|
||||
/** 删除指定通知渠道。 */
|
||||
export const deleteNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => del(`/api/v1/notifications/channels/${channelID}`, undefined, options);
|
||||
export const deleteNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => runContractRequest(/* signal 控制通知渠道删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/notifications/channels/{channel_id}', { params: { path: { channel_id: channelID } }, signal }), options);
|
||||
|
||||
/** 获取并展平按账号分组存储的消息通知绑定。 */
|
||||
export const getMessageNotifications = async (): Promise<{ /** 操作是否完成。 */ success: boolean; /** 展平后的绑定列表。 */ data: NotificationBinding[] }> => {
|
||||
// response 是按账号 ID 分组的通知绑定响应。
|
||||
const response = await get<Record<string, NotificationBinding[]>>('/api/v1/notifications/messages');
|
||||
const response = await runContractRequest(/* signal 控制消息通知列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/messages', { signal }));
|
||||
// bindings 是供页面直接渲染的扁平绑定集合。
|
||||
const bindings: NotificationBinding[] = [];
|
||||
for (const /* accountID、channelBindings 是当前账号及其原始渠道绑定列表。 */ [accountID, channelBindings] of Object.entries(response || {})) {
|
||||
@@ -91,26 +88,26 @@ export const getMessageNotifications = async (): Promise<{ /** 操作是否完
|
||||
};
|
||||
|
||||
/** 设置单个账号与渠道之间的启用状态。 */
|
||||
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 setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise<OperationResponse> => runContractRequest(/* signal 控制单账号通知开关更新请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_id: channelID, enabled }, signal }));
|
||||
|
||||
/** 删除单个消息通知绑定。 */
|
||||
export const deleteMessageNotification = async (notificationID: string): Promise<OperationResponse> => del(`/api/v1/notifications/messages/${notificationID}`);
|
||||
export const deleteMessageNotification = async (notificationID: string): Promise<OperationResponse> => runContractRequest(/* signal 控制单条通知删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/notifications/messages/{notification_id}', { params: { path: { notification_id: notificationID } }, signal }));
|
||||
|
||||
/** 删除指定账号的全部消息通知绑定。 */
|
||||
export const deleteAccountNotifications = async (accountID: string): Promise<OperationResponse> => del(`/api/v1/notifications/messages/account/${accountID}`);
|
||||
export const deleteAccountNotifications = async (accountID: string): Promise<OperationResponse> => runContractRequest(/* signal 控制账号通知清理请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/notifications/messages/account/{cid}', { params: { path: { cid: accountID } }, signal }));
|
||||
|
||||
/** 读取指定账号已绑定的通知渠道主键。 */
|
||||
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 : [];
|
||||
// response 是由 OpenAPI 约束的账号渠道绑定响应;未绑定时后端兼容返回 null。
|
||||
const response = await runContractRequest(/* signal 控制账号通知绑定读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, signal }), options);
|
||||
return response.channel_ids ?? [];
|
||||
};
|
||||
|
||||
/** 覆盖保存指定账号的通知渠道绑定。 */
|
||||
export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise<OperationResponse> => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_ids: channelIDs });
|
||||
export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise<OperationResponse> => runContractRequest(/* signal 控制账号通知绑定覆盖请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_ids: channelIDs }, signal }));
|
||||
|
||||
/** 向单一通知渠道发送测试投递。 */
|
||||
export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => post(`/api/v1/notifications/channels/${channelID}/test`, {}, options);
|
||||
export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => runContractRequest(/* signal 控制通知渠道测试投递的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels/{channel_id}/test', { params: { path: { channel_id: channelID } }, signal }), options);
|
||||
|
||||
/** 将系统配置响应转换为通知 SMTP 表单使用的状态模型。 */
|
||||
const normalizeSystemSettings = (settings: Record<string, unknown>): SystemSettings => {
|
||||
@@ -127,9 +124,9 @@ const normalizeSystemSettings = (settings: Record<string, unknown>): SystemSetti
|
||||
/** 获取通知 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);
|
||||
const response = await runContractRequest(/* signal 控制系统设置读取的取消和超时。 */ signal => contractClient.GET('/api/v1/settings/system', { signal }), options) as unknown as { /** data 是当前服务端系统设置。 */ data?: Record<string, unknown>; /** settings 是兼容字段。 */ settings?: Record<string, unknown> } & Record<string, unknown>;
|
||||
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);
|
||||
export const updateSystemSettings = async (settings: Partial<SystemSettings>, options?: RequestControlOptions): Promise<OperationResponse> => runContractRequest(/* signal 控制系统设置更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/settings/system', { body: normalizeSystemSettingsUpdate(settings), signal }), options);
|
||||
@@ -71,21 +71,21 @@ export const NotificationSmtpSettings: React.FC<NotificationSmtpSettingsProps> =
|
||||
<div className="p-2 rounded-xl bg-blue-50 text-blue-600"><Mail className="w-5 h-5" /></div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 服务器</label><input data-field="smtp_server" type="text" value={smtp.smtp_server || ''} onChange={handleTextChange} placeholder="smtp.qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 端口</label><input type="number" value={smtp.smtp_port || 587} onChange={handlePortChange} placeholder="587" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 服务器</label><input data-field="smtp_server" type="text" value={typeof smtp.smtp_server === 'string' ? smtp.smtp_server : ''} onChange={handleTextChange} placeholder="smtp.qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 端口</label><input type="number" value={typeof smtp.smtp_port === 'number' ? smtp.smtp_port : 587} onChange={handlePortChange} placeholder="587" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
</div>
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱</label><input data-field="smtp_user" type="email" value={smtp.smtp_user || ''} onChange={handleTextChange} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱</label><input data-field="smtp_user" type="email" value={typeof smtp.smtp_user === 'string' ? smtp.smtp_user : ''} onChange={handleTextChange} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">邮箱密码 / 授权码</label>
|
||||
<div className="relative">
|
||||
<input type={showPassword ? 'text' : 'password'} value={smtp.smtp_password || ''} onChange={handlePasswordChange} placeholder={smtp.smtp_password_configured ? '已配置,如需替换请输入新密码' : '输入密码或授权码'} className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" />
|
||||
<input type={showPassword ? 'text' : 'password'} value={typeof smtp.smtp_password === 'string' ? smtp.smtp_password : ''} onChange={handlePasswordChange} placeholder={smtp.smtp_password_configured ? '已配置,如需替换请输入新密码' : '输入密码或授权码'} className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" />
|
||||
<button type="button" onClick={handleTogglePassword} className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors">{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label><input data-field="smtp_from_name" type="text" value={smtp.smtp_from_name || ''} onChange={handleTextChange} placeholder="闲鱼自动回复系统" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱地址</label><input data-field="smtp_from_address" type="email" value={smtp.smtp_from_address || smtp.smtp_user || ''} onChange={handleTextChange} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label><input data-field="smtp_from_name" type="text" value={typeof smtp.smtp_from_name === 'string' ? smtp.smtp_from_name : ''} onChange={handleTextChange} placeholder="闲鱼自动回复系统" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱地址</label><input data-field="smtp_from_address" type="email" value={typeof smtp.smtp_from_address === 'string' ? smtp.smtp_from_address : (typeof smtp.smtp_user === 'string' ? smtp.smtp_user : '')} onChange={handleTextChange} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700"><input type="checkbox" checked={smtp.smtp_use_tls !== false} onChange={handleTlsChange} />STARTTLS(常用于 587 端口)</label>
|
||||
|
||||
@@ -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 '../../../shared/api-contract/notifications';
|
||||
import type { NotificationChannel,SystemSettings } from './api';
|
||||
import { createNotificationChannel,deleteNotificationChannel,getNotificationChannels,getSystemSettings,testNotificationChannel,updateNotificationChannel,updateSystemSettings } from './api';
|
||||
import { useNotifications } from './hooks';
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 SystemSettings UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface SystemSettings {
|
||||
/** 默认 AI 模型名称。 */
|
||||
ai_model?: string;
|
||||
/** 全局 AI API 密钥。 */
|
||||
ai_api_key?: string;
|
||||
/** 全局 AI API 密钥是否已在服务端配置。 */
|
||||
ai_api_key_configured?: boolean;
|
||||
/** 全局 AI API 地址。 */
|
||||
ai_api_url?: string;
|
||||
/** 全局 AI 基础地址。 */
|
||||
ai_base_url?: string;
|
||||
/** 系统默认回复文案。 */
|
||||
default_reply?: string;
|
||||
/** 是否允许注册新用户。 */
|
||||
registration_enabled?: boolean;
|
||||
/** 系统 SMTP 服务器地址。 */
|
||||
smtp_server?: string;
|
||||
/** 系统 SMTP 密码是否已在服务端配置。 */
|
||||
smtp_password_configured?: boolean;
|
||||
/** 服务端日志级别。 */
|
||||
log_level?: 'debug' | 'info' | 'warn' | 'error' | string;
|
||||
/** 服务端日志格式。 */
|
||||
log_format?: 'text' | 'json' | string;
|
||||
/** 续期日志保留天数。 */
|
||||
renewal_log_retention_days?: number;
|
||||
/** 远程验证码服务地址。 */
|
||||
'captcha.remote_service_url'?: string;
|
||||
/** 远程验证码服务密钥。 */
|
||||
'captcha.remote_secret_key'?: string;
|
||||
/** 远程验证码服务密钥是否已在服务端配置。 */
|
||||
'captcha.remote_secret_key_configured'?: boolean;
|
||||
/** 远程验证码服务 Cookie 配置。 */
|
||||
'captcha.remote_pass_cookies'?: boolean | string;
|
||||
/** 兼容未来配置键的扩展字段。 */
|
||||
/** 未知设置键只能承载服务端声明的标量值,敏感值不进入该 UI 模型。 */
|
||||
[key: string]: string | number | boolean | undefined;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 NotificationChannelType UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email';
|
||||
/** 由当前 feature adapter 归一后的 NotificationEventType UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type NotificationEventType =
|
||||
| 'account_offline'
|
||||
| 'account_recovered'
|
||||
| 'account_disabled'
|
||||
| 'security_verification'
|
||||
| 'token_renewal'
|
||||
| 'delivery_result'
|
||||
| 'system_error';
|
||||
|
||||
/** 由当前 feature adapter 归一后的 NotificationChannel UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface NotificationChannel {
|
||||
/** 通知渠道标识。 */
|
||||
id: string;
|
||||
/** 通知渠道名称。 */
|
||||
name: string;
|
||||
/** 通知渠道类型。 */
|
||||
type: NotificationChannelType;
|
||||
/** 通知渠道配置。 */
|
||||
config: Record<string, unknown>;
|
||||
/** 渠道绑定的事件类型。 */
|
||||
event_types?: NotificationEventType[];
|
||||
/** 通知渠道是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 创建时间。 */
|
||||
created_at?: string;
|
||||
/** 更新时间。 */
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
/** 通知绑定列表中的单条记录。 */
|
||||
/** 由当前 feature adapter 归一后的 NotificationBinding UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface NotificationBinding {
|
||||
/** 账号稳定标识,列表归一化后补充。 */
|
||||
cookie_id?: string;
|
||||
/** 绑定记录主键。 */
|
||||
id?: number;
|
||||
/** 通知渠道主键。 */
|
||||
channel_id: number;
|
||||
/** 通知渠道名称。 */
|
||||
channel_name: string;
|
||||
/** 绑定是否启用。 */
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
|
||||
/** 通知渠道接口返回的原始具名 DTO。 */
|
||||
/** 由当前 feature adapter 归一后的 NotificationChannelResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface NotificationChannelResponse {
|
||||
/** 通知渠道主键。 */
|
||||
id: number;
|
||||
/** 通知渠道名称。 */
|
||||
name: string;
|
||||
/** 通知渠道类型。 */
|
||||
type: string;
|
||||
/** 订阅事件类型 JSON 或兼容文本。 */
|
||||
event_types?: string;
|
||||
/** 通知渠道是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 所属用户主键。 */
|
||||
user_id?: number;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect,test } from 'vitest';
|
||||
import type { NotificationChannel } from '../../../shared/api-contract/notifications';
|
||||
import type { NotificationChannel } from './api';
|
||||
import { buildNotificationPayload,emptyNotificationForm,isCurrentNotificationRequest,normalizeNotificationForm,notificationErrorMessage,notificationEventSummary,validateNotificationForm } from './state';
|
||||
import type { NotificationForm } from './types';
|
||||
|
||||
|
||||
@@ -5,22 +5,50 @@ Item,
|
||||
OperationResponse,
|
||||
Order,
|
||||
OrderBatchResponse,
|
||||
OrderDTOResponse,OrderDetailResponse,
|
||||
OrderRefreshJobCancelResponse,
|
||||
OrderRefreshJobStartResponse,OrderRefreshJobStatusResponse,
|
||||
OrderDTOResponse,
|
||||
OrderRefreshJobCancelResponse,OrderRefreshJobStatusResponse,
|
||||
OrderRefreshResponse,
|
||||
OrderSingleRefreshResponse,
|
||||
PaginatedResponse
|
||||
} from '../../../shared/api-contract/orders';
|
||||
import { del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/orders';
|
||||
} from './models';
|
||||
import { contractClient, contractMultipartBody, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
export type * from './models';
|
||||
|
||||
/** 订单刷新前端最多轮询约 90 秒,超过该预算必须请求取消后端 worker。 */
|
||||
const orderRefreshPollLimit = 180;
|
||||
/** 订单刷新取消和终态复查使用独立五秒网络预算,不能复用已超时或已 Abort 的主信号。 */
|
||||
const orderRefreshCancelTimeoutMs = 5_000;
|
||||
|
||||
/** OrderListQuery 描述订单列表 operation 可传递的筛选和分页参数。 */
|
||||
type OrderListQuery = {
|
||||
/** 账号筛选标识。 */ cookie_id?: string;
|
||||
/** 订单状态筛选值。 */ status?: string;
|
||||
/** 用户输入的文本搜索条件。 */ search?: string;
|
||||
/** 页码,从一开始。 */ page: number;
|
||||
/** 每页最大行数。 */ page_size: number;
|
||||
};
|
||||
|
||||
/** OrderBatchTransportResponse 描述生成 operation 返回、尚未归一化状态枚举的批量订单结果。 */
|
||||
type OrderBatchTransportResponse = {
|
||||
/** 批次是否包含失败项。 */ partial_failure: boolean;
|
||||
/** 可展示的批次执行说明。 */ message: string;
|
||||
/** 可选的输入订单总数。 */ total?: number;
|
||||
/** 已成功处理的订单数量。 */ success_count: number;
|
||||
/** 已失败处理的订单数量。 */ failed_count: number;
|
||||
/** 每个订单的 transport 结果。 */ results: Array<{
|
||||
/** 平台订单标识。 */ order_id?: string;
|
||||
/** 服务端返回的处理状态。 */ status?: string;
|
||||
/** 单项是否成功。 */ success?: boolean;
|
||||
/** 单项处理说明。 */ message: string;
|
||||
/** 所属账号标识。 */ cookie_id?: string;
|
||||
/** 不确定远端结果的补偿记录标识。 */ reconciliation_id?: string;
|
||||
/** 本地补偿警告。 */ reconciliation_warning?: string;
|
||||
/** 当前业务处理阶段。 */ stage?: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
/** 订单刷新轮询选项仅控制前端等待行为;不改变后端任务、HTTP 路径或请求体契约。 */
|
||||
export interface OrderRefreshPollOptions extends RequestControlOptions {
|
||||
/** pollLimit 是本次前端最多读取任务状态的次数;省略时保持九十秒默认预算。 */
|
||||
@@ -30,13 +58,31 @@ export interface OrderRefreshPollOptions extends RequestControlOptions {
|
||||
}
|
||||
|
||||
/** 订单筛选器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => {
|
||||
// response 是账号摘要 transport DTO 集合,转换后只向订单 UI 暴露非敏感字段。
|
||||
const response = await runContractRequest(/* signal 是本次订单账号摘要请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options);
|
||||
return response.map(/* item 是当前待转换的账号摘要 DTO。 */ item => ({
|
||||
id: item.id,
|
||||
enabled: item.enabled,
|
||||
auto_confirm: item.auto_confirm,
|
||||
remark: item.remark,
|
||||
pause_duration: item.pause_duration,
|
||||
paused_until: item.paused_until,
|
||||
paused: item.paused,
|
||||
username: item.username,
|
||||
show_browser: item.show_browser,
|
||||
nickname: item.nickname,
|
||||
avatar_url: item.avatar_url,
|
||||
profile_error: item.profile_error,
|
||||
}));
|
||||
};
|
||||
|
||||
/** 订单关联商品展示读取当前商品索引。 */
|
||||
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options);
|
||||
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => runContractRequest(/* signal 控制订单页商品读取的取消和超时。 */ signal => contractClient.GET('/api/v1/items', { params: { query: { cookie_id: accountID } }, signal }), options) as unknown as Promise<Item[]>;
|
||||
|
||||
/** 管理员统计仍由订单域兼容 API 提供给历史管理页面。 */
|
||||
export const getAdminStats = async (): Promise<AdminStatsResponse> => get('/api/v1/admin/stats');
|
||||
export const getAdminStats = async (): Promise<AdminStatsResponse> =>
|
||||
runContractRequest(/* signal 是本次管理员统计请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/admin/stats', { signal }));
|
||||
// Orders
|
||||
// normalizeOrderStatus 归一化订单状态。
|
||||
const normalizeOrderStatus = (value: unknown): Order['status'] => {
|
||||
@@ -58,65 +104,92 @@ export const getOrders = async (
|
||||
options?: RequestControlOptions,
|
||||
): Promise<PaginatedResponse<Order>> => {
|
||||
// params 请求参数,用于当前 API 处理流程。
|
||||
const params: any = { page, page_size: pageSize };
|
||||
// params 是生成契约约束的订单筛选与分页查询参数。
|
||||
const params: OrderListQuery = { 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']);
|
||||
// response 是生成契约约束的订单分页 transport DTO。
|
||||
const response = await runContractRequest(/* signal 是本次订单分页请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/orders', {
|
||||
params: { query: params },
|
||||
signal,
|
||||
}), options);
|
||||
// legacyResponse 是保留给旧 handler 包装和测试夹具的适配视图,不扩散到 UI model。
|
||||
const legacyResponse = response as unknown;
|
||||
// pageResponse 是直接分页对象或 data/result 包装后的页面元数据。
|
||||
const pageResponse = objectFrom<Partial<PaginatedResponse<Order>> & { /** orders 是历史订单列表字段别名。 */ orders?: Order[] }>(legacyResponse, ['data', 'result']) || {};
|
||||
// rawOrders 是当前分页中的订单 transport DTO;兼容归一只在 adapter 内完成。
|
||||
const rawOrders = Array.isArray(pageResponse.orders) ? pageResponse.orders : collectionFrom<Order>(pageResponse.data, ['data', 'orders', 'items']);
|
||||
// orders 订单列表,用于当前 API 处理流程。
|
||||
const orders = rawOrders.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
|
||||
const orders = rawOrders.map(/* item 是当前需要归一化状态与数量的订单 DTO。 */ item => ({
|
||||
...item,
|
||||
id: item.id || item.order_id,
|
||||
id: item.order_id,
|
||||
order_status: normalizeOrderStatus(item.order_status),
|
||||
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
|
||||
total: pageResponse.total || orders.length,
|
||||
page: pageResponse.page || page,
|
||||
page_size: pageResponse.page_size || pageSize,
|
||||
total_pages: pageResponse.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}`);
|
||||
const result = await runContractRequest(/* signal 是本次订单详情请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/orders/{order_id}', {
|
||||
params: { path: { order_id: orderId } },
|
||||
signal,
|
||||
}));
|
||||
// data 是将可选 transport 字段归一为 UI 模型稳定字符串/布尔值后的订单详情。
|
||||
const data: OrderDTOResponse = {
|
||||
...result.data,
|
||||
spec_name: result.data.spec_name ?? '',
|
||||
spec_value: result.data.spec_value ?? '',
|
||||
is_bargain: result.data.is_bargain ?? 0,
|
||||
system_shipped: result.data.system_shipped ?? false,
|
||||
receiver_name: result.data.receiver_name ?? '',
|
||||
receiver_phone: result.data.receiver_phone ?? '',
|
||||
receiver_address: result.data.receiver_address ?? '',
|
||||
receiver_city: result.data.receiver_city ?? '',
|
||||
updated_at: result.data.updated_at ?? result.data.created_at,
|
||||
};
|
||||
return {
|
||||
success: true,
|
||||
data: result.data
|
||||
data
|
||||
};
|
||||
};
|
||||
|
||||
// updateOrder 更新订单。
|
||||
export const updateOrder = async (orderId: string, data: Partial<Order>): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/orders/${orderId}`, data);
|
||||
return runContractRequest(/* signal 是本次订单更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/orders/{order_id}', {
|
||||
params: { path: { order_id: orderId } },
|
||||
body: data,
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// deleteOrder 删除订单。
|
||||
export const deleteOrder = async (orderId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/orders/${orderId}`);
|
||||
return runContractRequest(/* signal 是本次订单删除请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/orders/{order_id}', {
|
||||
params: { path: { order_id: orderId } },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// syncOrders 同步订单。
|
||||
export const syncOrders = async (cookieId?: string, status?: string, options?: OrderRefreshPollOptions): 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);
|
||||
const start = await runContractRequest(/* signal 是本次订单刷新任务创建请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/refresh', {
|
||||
// body 是新版 JSON 筛选条件;服务端仍保留 multipart 兼容解析,但新版不再受上传边界影响。
|
||||
body: { cookie_id: cookieId, status },
|
||||
signal,
|
||||
}), options);
|
||||
// cancelOnAbort 在调用方取消轮询时通知服务端停止同一后台任务;取消命令使用独立信号,主请求已取消也能发出。
|
||||
const cancelOnAbort = () => {
|
||||
void cancelOrderRefreshJob(start.job_id, { timeoutMs: orderRefreshCancelTimeoutMs }).catch(/* 取消请求失败时忽略网络错误,主请求仍按取消语义结束。 */ () => undefined);
|
||||
@@ -131,7 +204,10 @@ export const syncOrders = async (cookieId?: string, status?: string, options?: O
|
||||
try {
|
||||
while (pollIndex < pollLimit) {
|
||||
// job 表示当前轮询得到的后台任务状态。
|
||||
const job = await get<OrderRefreshJobStatusResponse>(`/api/v1/orders/refresh/${start.job_id}`, undefined, options);
|
||||
const job = await runContractRequest(/* signal 是本次订单刷新状态轮询请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/orders/refresh/{job_id}', {
|
||||
params: { path: { job_id: start.job_id } },
|
||||
signal,
|
||||
}), options);
|
||||
if (job.status === 'succeeded' && job.result) {
|
||||
return job.result;
|
||||
}
|
||||
@@ -178,30 +254,70 @@ const cancelAndReadOrderRefreshJob = async (jobId: string): Promise<OrderRefresh
|
||||
} catch {
|
||||
// 取消返回冲突或网络错误时仍读取终态:任务可能已经在取消命令到达前结束。
|
||||
}
|
||||
return get<OrderRefreshJobStatusResponse>(`/api/v1/orders/refresh/${jobId}`, undefined, { timeoutMs: orderRefreshCancelTimeoutMs });
|
||||
return runContractRequest(/* signal 是本次订单刷新终态查询请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/orders/refresh/{job_id}', {
|
||||
params: { path: { job_id: jobId } },
|
||||
signal,
|
||||
}), { timeoutMs: orderRefreshCancelTimeoutMs });
|
||||
};
|
||||
|
||||
// cancelOrderRefreshJob 请求取消当前用户的订单刷新后台任务。
|
||||
export const cancelOrderRefreshJob = async (jobId: string, options?: RequestControlOptions): Promise<OrderRefreshJobCancelResponse> => {
|
||||
return del(`/api/v1/orders/refresh/${jobId}`, undefined, options);
|
||||
return runContractRequest(/* signal 是本次订单刷新取消请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/orders/refresh/{job_id}', {
|
||||
params: { path: { job_id: jobId } },
|
||||
signal,
|
||||
}), options);
|
||||
};
|
||||
|
||||
// syncSingleOrder 同步单个订单。
|
||||
export const syncSingleOrder = async (orderId: string): Promise<OrderSingleRefreshResponse> => {
|
||||
return post(`/api/v1/orders/${orderId}/refresh`);
|
||||
return runContractRequest(/* signal 是本次单订单刷新请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/{order_id}/refresh', {
|
||||
params: { path: { order_id: orderId } },
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
|
||||
// manualShipOrder 手动发货订单。
|
||||
export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise<OrderBatchResponse> => {
|
||||
return post('/api/v1/orders/manual-ship', {
|
||||
// response 是生成契约约束的批量发货 transport DTO,随后归一化为旧 UI 模型。
|
||||
const response = await runContractRequest(/* signal 是本次批量发货请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/manual-ship', {
|
||||
body: {
|
||||
order_ids: orderIds,
|
||||
ship_mode: shipMode,
|
||||
});
|
||||
},
|
||||
signal,
|
||||
}));
|
||||
return normalizeOrderBatchResponse(response);
|
||||
}
|
||||
|
||||
// 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);
|
||||
if (isFormData) {
|
||||
// response 是生成契约约束的文件导入 transport DTO。
|
||||
const response = await runContractRequest(/* signal 是本次订单表格导入请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/import', {
|
||||
body: contractMultipartBody(data),
|
||||
signal,
|
||||
}), options);
|
||||
return normalizeOrderBatchResponse(response);
|
||||
}
|
||||
// response 是生成契约约束的 JSON 导入 transport DTO。
|
||||
const response = await runContractRequest(/* signal 是本次订单 JSON 导入请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/import', {
|
||||
body: data,
|
||||
signal,
|
||||
}), options);
|
||||
return normalizeOrderBatchResponse(response);
|
||||
}
|
||||
|
||||
// normalizeOrderBatchResponse 将生成 transport DTO 转为兼容历史订单页面的受限结果状态。
|
||||
const normalizeOrderBatchResponse = (response: OrderBatchTransportResponse): OrderBatchResponse => ({
|
||||
partial_failure: response.partial_failure,
|
||||
message: response.message,
|
||||
total: response.total,
|
||||
success_count: response.success_count,
|
||||
failed_count: response.failed_count,
|
||||
results: (response.results || []).map(/* item 是当前待归一化的批量订单结果 DTO。 */ item => ({
|
||||
...item,
|
||||
status: item.status === 'failed' || item.status === 'succeeded' || item.status === 'reconciliation_required' ? item.status : undefined,
|
||||
})),
|
||||
});
|
||||
@@ -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 '../../../shared/api-contract/orders';
|
||||
import type { AccountDetail,Item } from './api';
|
||||
import { getAccountDetails,getItems,getOrders,importOrders } from './api';
|
||||
import { useOrderImport,useOrderQuery } from './hooks';
|
||||
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 PaginatedResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface PaginatedResponse<T> {
|
||||
/** 表示查询是否成功。 */
|
||||
success: boolean;
|
||||
/** 当前页数据。 */
|
||||
data: T[];
|
||||
/** 符合条件的总记录数。 */
|
||||
total: number;
|
||||
/** 当前页码。 */
|
||||
page: number;
|
||||
/** 每页记录数。 */
|
||||
page_size: number;
|
||||
/** 总页数。 */
|
||||
total_pages: number;
|
||||
/** 各触发类型的规则计数。 */
|
||||
trigger_counts?: Record<string, number>;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountDetail {
|
||||
/** 闲鱼账号稳定标识。 */
|
||||
id: string;
|
||||
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
|
||||
cookie_configured?: boolean;
|
||||
/** 账号是否允许运行。 */
|
||||
enabled: boolean;
|
||||
/** 是否自动确认订单。 */
|
||||
auto_confirm: boolean;
|
||||
/** 用户为账号设置的备注。 */
|
||||
remark?: string;
|
||||
/** 自动回复暂停时长,单位为分钟。 */
|
||||
pause_duration?: number;
|
||||
/** 暂停结束时间的 Unix 秒。 */
|
||||
paused_until?: number;
|
||||
/** 当前是否处于暂停状态。 */
|
||||
paused?: boolean;
|
||||
// 登录信息
|
||||
/** 用于密码登录的闲鱼用户名。 */
|
||||
username?: string;
|
||||
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
|
||||
login_password_configured?: boolean;
|
||||
/** 是否在密码登录时显示浏览器。 */
|
||||
show_browser?: boolean;
|
||||
// Frontend helpers
|
||||
/** 平台账号昵称。 */
|
||||
nickname?: string;
|
||||
/** 平台账号头像地址。 */
|
||||
avatar_url?: string;
|
||||
/** 资料刷新失败时的说明。 */
|
||||
profile_error?: string;
|
||||
/** 当前账号运行状态。 */
|
||||
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
|
||||
/** 当前运行状态的用户可见说明。 */
|
||||
runtime_message?: string;
|
||||
/** 当前运行实例是否已连接。 */
|
||||
runtime_connected?: boolean;
|
||||
/** 运行状态快照的更新时间。 */
|
||||
runtime_updated_at?: string;
|
||||
// AI设置
|
||||
/** 是否启用账号 AI 回复。 */
|
||||
ai_enabled?: boolean;
|
||||
/** 允许的最大折扣比例。 */
|
||||
max_discount_percent?: number;
|
||||
/** 允许的最大折扣金额。 */
|
||||
max_discount_amount?: number;
|
||||
/** 允许的最大砍价轮次。 */
|
||||
max_bargain_rounds?: number;
|
||||
/** 账号自定义提示词。 */
|
||||
custom_prompts?: string;
|
||||
// 账号级计划任务
|
||||
/** 是否启用自动评价。 */
|
||||
auto_rate_enabled?: boolean;
|
||||
/** 自动评价使用的文案。 */
|
||||
rate_content?: string;
|
||||
/** 是否启用每日擦亮。 */
|
||||
auto_polish_enabled?: boolean;
|
||||
/** 每日擦亮执行时间。 */
|
||||
polish_time?: string;
|
||||
/** 最近一次自动评价扫描时间。 */
|
||||
last_rate_scan_at?: number;
|
||||
/** 最近一次擦亮日期。 */
|
||||
last_polish_date?: string;
|
||||
/** 最近一次擦亮时间。 */
|
||||
last_polish_at?: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 OrderStatus UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type OrderStatus =
|
||||
| 'processing'
|
||||
| 'pending_ship'
|
||||
| 'shipped'
|
||||
| 'completed'
|
||||
| 'cancelled'
|
||||
| 'refunding'
|
||||
| 'unknown';
|
||||
|
||||
/** 由当前 feature adapter 归一后的 Order UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface Order {
|
||||
/** 订单本地数据库主键。 */
|
||||
id: string;
|
||||
/** 平台订单标识。 */
|
||||
order_id: string;
|
||||
/** 订单所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 订单关联商品标识。 */
|
||||
item_id: string;
|
||||
/** 商品标题。 */
|
||||
item_title?: string;
|
||||
/** 商品图片地址。 */
|
||||
item_image?: string;
|
||||
/** 商品价格文本。 */
|
||||
item_price?: string;
|
||||
/** 买家平台标识。 */
|
||||
buyer_id: string;
|
||||
/** 购买数量。 */
|
||||
quantity: number;
|
||||
/** 订单金额文本。 */
|
||||
amount: string;
|
||||
/** 前端归一化后的订单状态。 */
|
||||
status: OrderStatus;
|
||||
/** 服务端原始订单状态。 */
|
||||
order_status?: OrderStatus;
|
||||
/** 收货人姓名。 */
|
||||
receiver_name?: string;
|
||||
/** 收货人电话。 */
|
||||
receiver_phone?: string;
|
||||
/** 收货地址。 */
|
||||
receiver_address?: string;
|
||||
/** 订单创建时间。 */
|
||||
created_at?: string;
|
||||
/** 订单更新时间。 */
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface Item {
|
||||
/** 本地商品数据库主键。 */
|
||||
id: string | number;
|
||||
/** 商品所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 平台商品标识。 */
|
||||
item_id: string;
|
||||
/** 商品标题。 */
|
||||
item_title?: string;
|
||||
/** 商品描述。 */
|
||||
item_description?: string;
|
||||
/** 商品价格文本。 */
|
||||
item_price?: string;
|
||||
/** 商品主图地址。 */
|
||||
item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes
|
||||
/** 商品分类标识。 */
|
||||
item_category?: string;
|
||||
/** 商品详情原始 JSON。 */
|
||||
item_detail?: string;
|
||||
/** 是否启用多规格。 */
|
||||
is_multi_spec?: number | boolean;
|
||||
/** 是否按数量发货。 */
|
||||
multi_quantity_delivery?: number | boolean;
|
||||
/** 是否启用多数量发货兼容字段。 */
|
||||
is_multi_qty_ship?: number | boolean;
|
||||
}
|
||||
|
||||
/** 订单详情接口返回的原始具名订单 DTO。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderDTOResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderDTOResponse {
|
||||
/** 平台订单标识。 */
|
||||
order_id: string;
|
||||
/** 关联商品标识。 */
|
||||
item_id: string;
|
||||
/** 关联商品标题。 */
|
||||
item_title: string;
|
||||
/** 关联商品图片地址。 */
|
||||
item_image: string;
|
||||
/** 买家平台标识。 */
|
||||
buyer_id: string;
|
||||
/** 商品规格名称。 */
|
||||
spec_name: string;
|
||||
/** 商品规格值。 */
|
||||
spec_value: string;
|
||||
/** 购买数量文本。 */
|
||||
quantity: string;
|
||||
/** 实付金额文本。 */
|
||||
amount: string;
|
||||
/** 归一化订单状态。 */
|
||||
order_status: string;
|
||||
/** 兼容前端使用的订单状态别名。 */
|
||||
status: string;
|
||||
/** 所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 是否议价订单。 */
|
||||
is_bargain: number;
|
||||
/** 是否系统发货。 */
|
||||
system_shipped: boolean;
|
||||
/** 收货人姓名。 */
|
||||
receiver_name: string;
|
||||
/** 收货人电话。 */
|
||||
receiver_phone: string;
|
||||
/** 收货地址。 */
|
||||
receiver_address: string;
|
||||
/** 收货城市。 */
|
||||
receiver_city: string;
|
||||
/** 创建时间。 */
|
||||
created_at: string;
|
||||
/** 更新时间。 */
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** 订单详情接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderDetailResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderDetailResponse extends OrderDTOResponse {
|
||||
/** 表示查询是否完成。 */
|
||||
success: boolean;
|
||||
/** 新版客户端读取的订单对象。 */
|
||||
data: OrderDTOResponse;
|
||||
}
|
||||
|
||||
/** 订单单条刷新返回的远端详情。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderRefreshDetailResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderRefreshDetailResponse {
|
||||
/** 购买数量文本。 */
|
||||
quantity: string;
|
||||
/** 商品规格名称。 */
|
||||
spec_name: string;
|
||||
/** 商品规格值。 */
|
||||
spec_value: string;
|
||||
/** 归一化订单状态。 */
|
||||
order_status: string;
|
||||
/** 实付金额文本。 */
|
||||
amount: string;
|
||||
}
|
||||
|
||||
/** 订单单条刷新接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderSingleRefreshResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderSingleRefreshResponse {
|
||||
/** 表示刷新是否完成。 */
|
||||
success: boolean;
|
||||
/** 刷新结果说明。 */
|
||||
message: string;
|
||||
/** 刷新后的订单详情。 */
|
||||
order: OrderRefreshDetailResponse;
|
||||
}
|
||||
|
||||
/** 订单批量变更接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderBatchResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderBatchResponse {
|
||||
/** 表示批量操作是否存在部分失败。 */
|
||||
partial_failure: boolean;
|
||||
/** 批量操作结果说明。 */
|
||||
message: string;
|
||||
/** 订单总数,导入接口提供。 */
|
||||
total?: number;
|
||||
/** 成功处理数量。 */
|
||||
success_count: number;
|
||||
/** 失败处理数量。 */
|
||||
failed_count: number;
|
||||
/** 逐订单兼容结果行。 */
|
||||
results: OrderBatchResult[];
|
||||
}
|
||||
|
||||
/** 订单批量接口的逐订单结果行。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderBatchResult UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderBatchResult {
|
||||
/** 订单平台标识。 */
|
||||
order_id?: string;
|
||||
/** 订单动作状态:failed、succeeded 或 reconciliation_required。 */
|
||||
status?: 'failed' | 'succeeded' | 'reconciliation_required';
|
||||
/** 表示该订单是否处理成功。 */
|
||||
success?: boolean;
|
||||
/** 该订单处理结果说明。 */
|
||||
message: string;
|
||||
/** 兼容接口可能返回的账号标识。 */
|
||||
cookie_id?: string;
|
||||
/** 待补偿记录标识。 */
|
||||
reconciliation_id?: string;
|
||||
/** 本地状态或补偿记录写入警告。 */
|
||||
reconciliation_warning?: string;
|
||||
/** 兼容接口可能返回的处理阶段。 */
|
||||
stage?: string;
|
||||
/** 允许后端保留尚未结构化的扩展字段。 */
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
|
||||
/** 管理员全局统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AdminStats UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AdminStats {
|
||||
/** 管理员可见的用户总数。 */ total_users: number;
|
||||
/** 当前用户拥有的账号总数。 */ total_cookies: number;
|
||||
/** 已启用账号数量。 */ active_cookies: number;
|
||||
/** 卡券组总数。 */ total_cards: number;
|
||||
/** 关键词规则总数。 */ total_keywords: number;
|
||||
/** 订单总数。 */ total_orders: number;
|
||||
}
|
||||
|
||||
/** 订单域兼容页面使用的数据概览字段。 */
|
||||
export interface DashboardStats {
|
||||
/** 当前用户的账号总数。 */ total_cookies: number;
|
||||
/** 已启用账号数量。 */ active_cookies: number;
|
||||
/** 卡券组总数。 */ total_cards: number;
|
||||
/** 关键词规则总数。 */ total_keywords: number;
|
||||
/** 订单总数。 */ total_orders: number;
|
||||
/** 可用卡券库存。 */ available_card_stock: number;
|
||||
}
|
||||
|
||||
/** 管理员全局统计响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AdminStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AdminStatsResponse extends AdminStats {}
|
||||
|
||||
/** 当前用户数据概览响应。 */
|
||||
/** 由当前 feature adapter 归一后的 DashboardStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface DashboardStatsResponse extends DashboardStats {}
|
||||
|
||||
/** 订单列表刷新逐项结果。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderRefreshResultResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderRefreshResultResponse {
|
||||
/** 结果所属账号标识。 */
|
||||
cookie_id?: string;
|
||||
/** 当前处理阶段。 */
|
||||
stage?: string;
|
||||
/** 当前项是否处理成功。 */
|
||||
success: boolean;
|
||||
/** 结果说明。 */
|
||||
message?: string;
|
||||
/** 发现的新订单数量。 */
|
||||
discovered?: number;
|
||||
/** 更新的订单数量。 */
|
||||
updated?: number;
|
||||
/** 标记删除的订单数量。 */
|
||||
/** soft_deleted 表示该订单是否已被本次刷新标记为软删除。 */
|
||||
soft_deleted?: boolean;
|
||||
/** 订单平台标识。 */
|
||||
order_id?: string;
|
||||
/** 结果错误说明。 */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** 订单列表刷新统计摘要。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderRefreshSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderRefreshSummaryResponse {
|
||||
/** 发现的新订单数量。 */
|
||||
discovered: number;
|
||||
/** 订单列表更新数量。 */
|
||||
list_updated: number;
|
||||
/** 标记删除数量。 */
|
||||
soft_deleted: number;
|
||||
/** 需要补全详情的订单数量。 */
|
||||
detail_total: number;
|
||||
/** 本次处理订单总数。 */
|
||||
total: number;
|
||||
/** 状态发生变化数量。 */
|
||||
updated: number;
|
||||
/** 状态未变化数量。 */
|
||||
no_change: number;
|
||||
/** 刷新失败数量。 */
|
||||
failed: number;
|
||||
}
|
||||
|
||||
/** 订单列表刷新响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderRefreshResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderRefreshResponse {
|
||||
/** 是否存在部分失败。 */
|
||||
partial_failure: boolean;
|
||||
/** 刷新结果说明。 */
|
||||
message: string;
|
||||
/** 刷新统计摘要。 */
|
||||
summary: OrderRefreshSummaryResponse;
|
||||
/** 逐项兼容结果。 */
|
||||
results: OrderRefreshResultResponse[];
|
||||
}
|
||||
|
||||
/** 创建订单刷新后台任务的响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderRefreshJobStartResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderRefreshJobStartResponse {
|
||||
/** 任务是否创建成功。 */
|
||||
success: boolean;
|
||||
/** 后台任务标识。 */
|
||||
job_id: string;
|
||||
/** 任务当前状态。 */
|
||||
status: 'queued' | 'running';
|
||||
}
|
||||
|
||||
/** 查询订单刷新后台任务的响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderRefreshJobStatusResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderRefreshJobStatusResponse {
|
||||
/** 查询是否成功。 */
|
||||
success: boolean;
|
||||
/** 后台任务标识。 */
|
||||
job_id: string;
|
||||
/** 任务当前状态。 */
|
||||
status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled';
|
||||
/** 任务失败原因。 */
|
||||
error_message?: string;
|
||||
/** 任务成功后的订单刷新结果。 */
|
||||
result?: OrderRefreshResponse;
|
||||
}
|
||||
|
||||
/** 取消订单刷新后台任务的响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OrderRefreshJobCancelResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OrderRefreshJobCancelResponse {
|
||||
/** 取消命令是否成功应用。 */
|
||||
success: boolean;
|
||||
/** 被取消的任务标识。 */
|
||||
job_id: string;
|
||||
/** 取消后的任务状态。 */
|
||||
status: 'cancelled';
|
||||
}
|
||||
@@ -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,OrderRefreshResponse } from '../../../shared/api-contract/orders';
|
||||
import type { Order,OrderRefreshResponse } from './api';
|
||||
import { useOrderActions } from './orderActions';
|
||||
|
||||
// orderActionMocks 保存订单动作 Hook 测试使用的 API 替身。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { Order } from '../../../../shared/api-contract/orders';
|
||||
import type { Order } from '../api';
|
||||
|
||||
// orderListMocks 保存订单页面测试使用的 Hook、API 和子组件替身。
|
||||
const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共享替身。 */ () => ({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import ReactDOMServer from 'react-dom/server';
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import type { NotificationChannel,SystemSettings } from '../../shared/api-contract/common';
|
||||
import type { NotificationChannel } from './notifications/api';
|
||||
import type { SystemSettings } from './settings/api';
|
||||
import { CardIcon } from './cards/components/CardIcon';
|
||||
import { BatchPhaseIndicator } from './items/components/BatchPhaseIndicator';
|
||||
import { NotificationChannelList } from './notifications/components/NotificationChannelList';
|
||||
|
||||
@@ -14,19 +14,20 @@ MutationIDResponse,OperationResponse,
|
||||
PaginatedResponse,
|
||||
ReplyRule,
|
||||
ShippingRule
|
||||
} from '../../../shared/api-contract/automation';
|
||||
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
} from './models';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/automation';
|
||||
export type * from './models';
|
||||
|
||||
/** 自动化规则筛选器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => runContractRequest(/* signal 控制规则页账号摘要读取的取消和超时。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options);
|
||||
|
||||
/** 自动化动作编辑器读取可选卡券组。 */
|
||||
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => get('/api/v1/cards', undefined, options);
|
||||
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => runContractRequest(/* signal 控制规则页卡券读取的取消和超时。 */ signal => contractClient.GET('/api/v1/cards', { signal }), options) as unknown as Promise<Card[]>;
|
||||
|
||||
/** 自动化规则商品选择器读取商品索引。 */
|
||||
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options);
|
||||
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => runContractRequest(/* signal 控制规则页商品读取的取消和超时。 */ signal => contractClient.GET('/api/v1/items', { params: { query: { cookie_id: accountID } }, signal }), options) as unknown as Promise<Item[]>;
|
||||
// Rules - 自动化规则
|
||||
const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
|
||||
id: String(item.id),
|
||||
@@ -77,7 +78,7 @@ const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map(/*
|
||||
// getShippingRules 读取发货规则列表。
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const res = await get<unknown>('/api/v1/automation-rules');
|
||||
const res = await runContractRequest(/* signal 控制自动化规则列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/automation-rules', { signal })) as unknown;
|
||||
// rules 规则列表,用于当前 API 处理流程。
|
||||
const rules = collectionFrom<AutomationRuleResponse>(res, ['data', 'rules', 'items']);
|
||||
return normalizeShippingRules(rules);
|
||||
@@ -102,14 +103,7 @@ export const getShippingRulesPage = async ({
|
||||
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,
|
||||
});
|
||||
const response = await runContractRequest(/* signal 控制自动化规则分页读取的取消和超时。 */ signal => contractClient.GET('/api/v1/automation-rules', { params: { query: { page: requestedPage, page_size: pageSize, cookie_id: cookieId, trigger_type: triggerType, enabled, search: search?.trim() } }, signal })) as unknown;
|
||||
// rules 规则列表,用于当前 API 处理流程。
|
||||
// page 是兼容直接分页对象和 data 包裹后的分页元数据。
|
||||
const pageMeta = objectFrom<Partial<AutomationRulePageResponse>>(response, ['data', 'result']) || {};
|
||||
@@ -152,6 +146,7 @@ export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<O
|
||||
const triggerType = rule.trigger_type || 'order_paid';
|
||||
// triggerName 触发名称,用于当前 API 处理流程。
|
||||
const triggerName: Record<string, string> = {
|
||||
order_created: '拍下未付款自动改价',
|
||||
order_paid: '付款后自动发货',
|
||||
buyer_reviewed: '评价后发送赠品',
|
||||
review_missing_timeout: '超时未评价求评价',
|
||||
@@ -207,11 +202,13 @@ export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<O
|
||||
sort_order: action.sort_order || index + 1,
|
||||
})),
|
||||
};
|
||||
return rule.id ? put(`/api/v1/automation-rules/${rule.id}`, payload) : post('/api/v1/automation-rules', payload);
|
||||
return rule.id
|
||||
? runContractRequest(/* signal 控制自动化规则更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/automation-rules/{rule_id}', { params: { path: { rule_id: String(rule.id) } }, body: payload as never, signal }))
|
||||
: runContractRequest(/* signal 控制自动化规则创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/automation-rules', { body: payload as never, signal }));
|
||||
}
|
||||
|
||||
// deleteShippingRule 删除发货规则。
|
||||
export const deleteShippingRule = async (id: string): Promise<OperationResponse> => del(`/api/v1/automation-rules/${id}`);
|
||||
export const deleteShippingRule = async (id: string): Promise<OperationResponse> => runContractRequest(/* signal 控制自动化规则删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/automation-rules/{rule_id}', { params: { path: { rule_id: id } }, signal }));
|
||||
|
||||
export interface AutomationRunIssue {
|
||||
/** id 表示标识。 */ id: number;
|
||||
@@ -238,7 +235,7 @@ export interface DeferredAutomationIssue {
|
||||
// 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');
|
||||
const response = await runContractRequest(/* signal 控制自动化问题读取的取消和超时。 */ signal => contractClient.GET('/api/v1/automation-issues', { signal })) as unknown;
|
||||
// result 是去除历史包裹后的自动化问题对象。
|
||||
const result = objectFrom<Partial<AutomationIssuesEnvelope>>(response, ['data', 'result']) || {};
|
||||
return {
|
||||
@@ -249,11 +246,11 @@ export const getAutomationIssues = async (): Promise<{ /** runs 表示运行记
|
||||
|
||||
// resolveAutomationRun 处理自动化运行记录。
|
||||
export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise<OperationResponse> =>
|
||||
post(`/api/v1/automation-runs/${id}/resolve`, { resolution });
|
||||
runContractRequest(/* signal 控制自动化运行处理请求的取消和超时。 */ signal => contractClient.POST('/api/v1/automation-runs/{run_id}/resolve', { params: { path: { run_id: String(id) } }, body: { resolution } as never, signal }));
|
||||
|
||||
// resolveDeferredAutomationTask 处理延迟自动化任务。
|
||||
export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise<OperationResponse> =>
|
||||
post(`/api/v1/automation-pending-tasks/${id}/resolve`, { resolution });
|
||||
runContractRequest(/* signal 控制待处理自动化任务请求的取消和超时。 */ signal => contractClient.POST('/api/v1/automation-pending-tasks/{task_id}/resolve', { params: { path: { task_id: String(id) } }, body: { resolution } as never, signal }));
|
||||
|
||||
// Rules - 关键词回复规则 (使用关键词API)
|
||||
type KeywordRowPayload = {
|
||||
@@ -278,7 +275,7 @@ const normalizeKeywordRow = (item: any): KeywordRowPayload => ({
|
||||
// getKeywordRowsWithType 读取带类型的关键词规则。
|
||||
const getKeywordRowsWithType = async (cookieId: string): Promise<KeywordRowPayload[]> => {
|
||||
// existing 已有规则,用于当前 API 处理流程。
|
||||
const existing = await get<unknown>(`/api/v1/reply-rules/${cookieId}/typed`);
|
||||
const existing = await runContractRequest(/* signal 控制关键词规则读取的取消和超时。 */ signal => contractClient.GET('/api/v1/reply-rules/{cid}/typed', { params: { path: { cid: cookieId } }, signal })) as unknown;
|
||||
return collectionFrom<KeywordTypedResponse>(existing, ['data', 'items', 'rules']).map(normalizeKeywordRow);
|
||||
};
|
||||
|
||||
@@ -312,20 +309,20 @@ export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string
|
||||
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);
|
||||
? runContractRequest(/* signal 控制关键词规则更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/reply-rules/{cid}/typed/{id}', { params: { path: { cid: cookieId, id: String(rule.id) } }, body: payload as never, signal }))
|
||||
: runContractRequest(/* signal 控制关键词规则创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/reply-rules/{cid}/items', { params: { path: { cid: cookieId } }, body: payload as never, signal }));
|
||||
}
|
||||
|
||||
// deleteReplyRule 删除回复规则。
|
||||
export const deleteReplyRule = async (id: string, cookieId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/reply-rules/${cookieId}/typed/${id}`);
|
||||
return runContractRequest(/* signal 控制关键词规则删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/reply-rules/{cid}/typed/{id}', { params: { path: { cid: cookieId, id } }, signal }));
|
||||
}
|
||||
|
||||
|
||||
// Default Reply
|
||||
// getDefaultReplies 读取默认回复列表。
|
||||
export const getDefaultReplies = async (): Promise<Record<string, DefaultReplyResponse>> => {
|
||||
const response = await get<unknown>('/api/v1/default-replies');
|
||||
const response = await runContractRequest(/* signal 控制默认回复列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/default-replies', { signal })) as unknown;
|
||||
// replies 是兼容直接映射、data 包裹和 null 的默认回复索引。
|
||||
return objectFrom<Record<string, DefaultReplyResponse>>(response, ['data', 'replies', 'items']) || {};
|
||||
};
|
||||
@@ -333,7 +330,7 @@ export const getDefaultReplies = async (): Promise<Record<string, DefaultReplyRe
|
||||
// getDefaultReply 读取默认回复。
|
||||
export const getDefaultReply = async (cookieId: string): Promise<DefaultReply> => {
|
||||
// result 接口响应结果,用于当前 API 处理流程。
|
||||
const response = await get<unknown>(`/api/v1/default-replies/${cookieId}`);
|
||||
const response = await runContractRequest(/* signal 控制默认回复读取的取消和超时。 */ signal => contractClient.GET('/api/v1/default-replies/{cid}', { params: { path: { cid: cookieId } }, signal })) as unknown;
|
||||
// result 是兼容直接默认回复和 data 包裹后的对象。
|
||||
const result = objectFrom<Partial<DefaultReplyResponse>>(response, ['data', 'result']) || {};
|
||||
return {
|
||||
@@ -347,20 +344,20 @@ export const getDefaultReply = async (cookieId: string): Promise<DefaultReply> =
|
||||
|
||||
// updateDefaultReply 更新默认回复。
|
||||
export const updateDefaultReply = async (cookieId: string, data: Partial<DefaultReply>): Promise<OperationResponse> => {
|
||||
return put(`/api/v1/default-replies/${cookieId}`, {
|
||||
return runContractRequest(/* signal 控制默认回复更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/default-replies/{cid}', { params: { path: { cid: cookieId }, }, body: {
|
||||
enabled: data.enabled ?? false,
|
||||
reply_content: data.reply_content || '',
|
||||
reply_once: data.reply_once ?? false,
|
||||
reply_image_url: data.reply_image_url || ''
|
||||
});
|
||||
} as never, signal }));
|
||||
};
|
||||
|
||||
// deleteDefaultReply 删除默认回复。
|
||||
export const deleteDefaultReply = async (cookieId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/default-replies/${cookieId}`);
|
||||
return runContractRequest(/* signal 控制默认回复删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/default-replies/{cid}', { params: { path: { cid: cookieId } }, signal }));
|
||||
};
|
||||
|
||||
// clearDefaultReplyRecords 清理默认回复记录。
|
||||
export const clearDefaultReplyRecords = async (cookieId: string): Promise<OperationResponse> => {
|
||||
return post(`/api/v1/default-replies/${cookieId}/clear-records`, {});
|
||||
return runContractRequest(/* signal 控制默认回复记录清理请求的取消和超时。 */ signal => contractClient.POST('/api/v1/default-replies/{cid}/clear-records', { params: { path: { cid: cookieId } }, body: {} as never, signal }));
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail,Card,DefaultReply,Item,ReplyRule,ShippingRule } from '../../../shared/api-contract/automation';
|
||||
import type { AccountDetail,Card,DefaultReply,Item,ReplyRule,ShippingRule } from './api';
|
||||
import {
|
||||
getAccountDetails,
|
||||
getAutomationIssues,
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 PaginatedResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface PaginatedResponse<T> {
|
||||
/** 表示查询是否成功。 */
|
||||
success: boolean;
|
||||
/** 当前页数据。 */
|
||||
data: T[];
|
||||
/** 符合条件的总记录数。 */
|
||||
total: number;
|
||||
/** 当前页码。 */
|
||||
page: number;
|
||||
/** 每页记录数。 */
|
||||
page_size: number;
|
||||
/** 总页数。 */
|
||||
total_pages: number;
|
||||
/** 各触发类型的规则计数。 */
|
||||
trigger_counts?: Record<string, number>;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AccountDetail {
|
||||
/** 闲鱼账号稳定标识。 */
|
||||
id: string;
|
||||
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
|
||||
cookie_configured?: boolean;
|
||||
/** 账号是否允许运行。 */
|
||||
enabled: boolean;
|
||||
/** 是否自动确认订单。 */
|
||||
auto_confirm: boolean;
|
||||
/** 用户为账号设置的备注。 */
|
||||
remark?: string;
|
||||
/** 自动回复暂停时长,单位为分钟。 */
|
||||
pause_duration?: number;
|
||||
/** 暂停结束时间的 Unix 秒。 */
|
||||
paused_until?: number;
|
||||
/** 当前是否处于暂停状态。 */
|
||||
paused?: boolean;
|
||||
// 登录信息
|
||||
/** 用于密码登录的闲鱼用户名。 */
|
||||
username?: string;
|
||||
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
|
||||
login_password_configured?: boolean;
|
||||
/** 是否在密码登录时显示浏览器。 */
|
||||
show_browser?: boolean;
|
||||
// Frontend helpers
|
||||
/** 平台账号昵称。 */
|
||||
nickname?: string;
|
||||
/** 平台账号头像地址。 */
|
||||
avatar_url?: string;
|
||||
/** 资料刷新失败时的说明。 */
|
||||
profile_error?: string;
|
||||
/** 当前账号运行状态。 */
|
||||
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
|
||||
/** 当前运行状态的用户可见说明。 */
|
||||
runtime_message?: string;
|
||||
/** 当前运行实例是否已连接。 */
|
||||
runtime_connected?: boolean;
|
||||
/** 运行状态快照的更新时间。 */
|
||||
runtime_updated_at?: string;
|
||||
// AI设置
|
||||
/** 是否启用账号 AI 回复。 */
|
||||
ai_enabled?: boolean;
|
||||
/** 允许的最大折扣比例。 */
|
||||
max_discount_percent?: number;
|
||||
/** 允许的最大折扣金额。 */
|
||||
max_discount_amount?: number;
|
||||
/** 允许的最大砍价轮次。 */
|
||||
max_bargain_rounds?: number;
|
||||
/** 账号自定义提示词。 */
|
||||
custom_prompts?: string;
|
||||
// 账号级计划任务
|
||||
/** 是否启用自动评价。 */
|
||||
auto_rate_enabled?: boolean;
|
||||
/** 自动评价使用的文案。 */
|
||||
rate_content?: string;
|
||||
/** 是否启用每日擦亮。 */
|
||||
auto_polish_enabled?: boolean;
|
||||
/** 每日擦亮执行时间。 */
|
||||
polish_time?: string;
|
||||
/** 最近一次自动评价扫描时间。 */
|
||||
last_rate_scan_at?: number;
|
||||
/** 最近一次擦亮日期。 */
|
||||
last_polish_date?: string;
|
||||
/** 最近一次擦亮时间。 */
|
||||
last_polish_at?: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 Card UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface Card {
|
||||
/** 卡券组数值主键。 */
|
||||
id: number;
|
||||
/** 卡券组名称。 */
|
||||
name: string;
|
||||
/** 卡券组类型。 */
|
||||
type: 'api' | 'text' | 'data' | 'image';
|
||||
/** 卡券组说明。 */
|
||||
description?: string;
|
||||
/** 卡券组是否启用。 */
|
||||
enabled: boolean;
|
||||
// 文本类型
|
||||
text_content?: string;
|
||||
// 批量数据类型
|
||||
data_content?: string;
|
||||
// API 类型配置
|
||||
api_config?: {
|
||||
/** API 卡券请求地址。 */
|
||||
url: string;
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求超时时间。 */
|
||||
timeout_seconds: number;
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled: boolean;
|
||||
/** 是否配置了请求头模板;具体值不会进入前端。 */
|
||||
headers_configured: boolean;
|
||||
/** 是否配置了请求参数模板;具体值不会进入前端。 */
|
||||
params_configured: boolean;
|
||||
/** 配置是否可用于规则发货。 */
|
||||
ready: boolean;
|
||||
/** 配置无效时的脱敏错误说明。 */
|
||||
validation_error?: string;
|
||||
};
|
||||
// 图片类型
|
||||
/** 图片卡券地址。 */
|
||||
image_url?: string;
|
||||
// 通用配置
|
||||
/** 卡券发送延迟秒数。 */
|
||||
delay_seconds?: number;
|
||||
// 多规格配置
|
||||
/** 是否支持多规格。 */
|
||||
is_multi_spec?: boolean;
|
||||
/** 规格名称。 */
|
||||
spec_name?: string;
|
||||
/** 规格值。 */
|
||||
spec_value?: string;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface Item {
|
||||
/** 本地商品数据库主键。 */
|
||||
id: string | number;
|
||||
/** 商品所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 平台商品标识。 */
|
||||
item_id: string;
|
||||
/** 商品标题。 */
|
||||
item_title?: string;
|
||||
/** 商品描述。 */
|
||||
item_description?: string;
|
||||
/** 商品价格文本。 */
|
||||
item_price?: string;
|
||||
/** 商品主图地址。 */
|
||||
item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes
|
||||
/** 商品分类标识。 */
|
||||
item_category?: string;
|
||||
/** 商品详情原始 JSON。 */
|
||||
item_detail?: string;
|
||||
/** 是否启用多规格。 */
|
||||
is_multi_spec?: number | boolean;
|
||||
/** 是否按数量发货。 */
|
||||
multi_quantity_delivery?: number | boolean;
|
||||
/** 是否启用多数量发货兼容字段。 */
|
||||
is_multi_qty_ship?: number | boolean;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AutomationTriggerType UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type AutomationTriggerType = 'order_created' | 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout';
|
||||
/** 由当前 feature adapter 归一后的 AutomationActionType UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export type AutomationActionType = 'confirm_shipment' | 'send_card' | 'send_text' | 'adjust_price';
|
||||
|
||||
// Rules
|
||||
/** 由当前 feature adapter 归一后的 ShippingRule UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ShippingRule {
|
||||
/** 规则标识。 */
|
||||
id: string;
|
||||
/** 规则名称。 */
|
||||
name: string;
|
||||
/** 规则触发类型。 */
|
||||
trigger_type: AutomationTriggerType;
|
||||
/** 规则匹配关键词。 */
|
||||
item_keyword: string; // Legacy UI helper
|
||||
/** 规则限定的账号标识。 */
|
||||
cookie_id?: string;
|
||||
/** 规则限定的商品标识。 */
|
||||
item_id?: string;
|
||||
/** 规则限定的商品标题。 */
|
||||
item_title?: string;
|
||||
/** 首个发卡动作使用的卡券组 ID。 */
|
||||
card_group_id: number; // First send_card action card id
|
||||
/** 首个发卡动作使用的卡券组名称。 */
|
||||
card_group_name?: string; // UI helper
|
||||
/** 规则优先级。 */
|
||||
priority: number;
|
||||
/** 规则是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 规则原始配置 JSON。 */
|
||||
config_json?: string;
|
||||
/** 规则动作列表。 */
|
||||
actions: AutomationAction[];
|
||||
/** 规则规格变体列表。 */
|
||||
variants: ShippingVariant[];
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AutomationAction UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AutomationAction {
|
||||
/** 动作标识。 */
|
||||
id?: string;
|
||||
/** 动作类型。 */
|
||||
action_type: AutomationActionType;
|
||||
/** 动作使用的卡券组 ID。 */
|
||||
card_id?: number;
|
||||
/** 动作使用的卡券组名称。 */
|
||||
card_name?: string;
|
||||
/** 本次发放数量。 */
|
||||
delivery_count?: number;
|
||||
/** 文本消息模板。 */
|
||||
message_template?: string;
|
||||
/** 动作延迟秒数。 */
|
||||
delay_seconds?: number;
|
||||
/** 动作原始配置 JSON。 */
|
||||
config_json?: string;
|
||||
/** 动作是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 动作排序序号。 */
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 ShippingVariant UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ShippingVariant {
|
||||
/** 规格变体标识。 */
|
||||
id?: string;
|
||||
/** 规格名称。 */
|
||||
spec_name: string;
|
||||
/** 规格值。 */
|
||||
spec_value: string;
|
||||
/** 变体使用的卡券组 ID。 */
|
||||
card_id: number;
|
||||
/** 变体使用的卡券组名称。 */
|
||||
card_name?: string;
|
||||
/** 卡券类型。 */
|
||||
card_type?: Card['type'];
|
||||
/** 变体发放数量。 */
|
||||
delivery_count: number;
|
||||
/** 变体是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 是否覆盖动作级延迟。 */
|
||||
delay_override?: boolean;
|
||||
/** 变体延迟秒数。 */
|
||||
delay_seconds?: number;
|
||||
/** 变体原始配置 JSON。 */
|
||||
config_json?: string;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 ReplyRule UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ReplyRule {
|
||||
/** 回复规则标识。 */
|
||||
id: string;
|
||||
/** 触发关键词。 */
|
||||
keyword: string;
|
||||
/** 回复正文。 */
|
||||
reply_content: string;
|
||||
/** 关键词匹配方式。 */
|
||||
match_type: 'exact' | 'fuzzy';
|
||||
/** 规则是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 规则限定的商品标识。 */
|
||||
item_id?: string;
|
||||
/** 回复类型。 */
|
||||
type?: 'text' | 'image';
|
||||
/** 图片回复地址。 */
|
||||
image_url?: string;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 DefaultReply UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface DefaultReply {
|
||||
/** 账号稳定标识。 */
|
||||
cookie_id: string;
|
||||
/** 默认回复是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 默认回复正文。 */
|
||||
reply_content: string;
|
||||
/** 是否对同一会话只回复一次。 */
|
||||
reply_once: boolean;
|
||||
/** 默认图片回复地址。 */
|
||||
reply_image_url?: string;
|
||||
}
|
||||
|
||||
/** 自动化规则动作的原始具名 DTO。 */
|
||||
/** 由当前 feature adapter 归一后的 AutomationActionResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AutomationActionResponse {
|
||||
/** 动作稳定标识。 */
|
||||
id: number;
|
||||
/** 动作类型。 */
|
||||
action_type: string;
|
||||
/** 关联卡券组标识。 */
|
||||
card_id: number;
|
||||
/** 关联卡券组名称。 */
|
||||
card_name: string;
|
||||
/** 发送数量。 */
|
||||
delivery_count: number;
|
||||
/** 消息模板。 */
|
||||
message_template: string;
|
||||
/** 延迟秒数。 */
|
||||
delay_seconds: number;
|
||||
/** 扩展配置 JSON。 */
|
||||
config_json: string;
|
||||
/** 是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 执行顺序。 */
|
||||
sort_order: number;
|
||||
}
|
||||
|
||||
/** 自动化规则的原始具名 DTO。 */
|
||||
/** 由当前 feature adapter 归一后的 AutomationRuleResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AutomationRuleResponse {
|
||||
/** 规则稳定标识。 */
|
||||
id: number;
|
||||
/** 所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 关联商品标识。 */
|
||||
item_id: string;
|
||||
/** 关联商品标题。 */
|
||||
item_title: string;
|
||||
/** 规则名称。 */
|
||||
name: string;
|
||||
/** 触发类型。 */
|
||||
trigger_type: string;
|
||||
/** 是否启用。 */
|
||||
enabled: boolean;
|
||||
/** 规则优先级。 */
|
||||
priority: number;
|
||||
/** 扩展配置 JSON。 */
|
||||
config_json: string;
|
||||
/** 规则动作列表。 */
|
||||
actions: AutomationActionResponse[];
|
||||
/** 创建时间。 */
|
||||
created_at: string;
|
||||
/** 更新时间。 */
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** 自动化规则分页接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AutomationRulePageResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AutomationRulePageResponse {
|
||||
/** 表示查询是否完成。 */
|
||||
success: boolean;
|
||||
/** 当前页规则列表。 */
|
||||
data: AutomationRuleResponse[];
|
||||
/** 规则总数。 */
|
||||
total: number;
|
||||
/** 当前页码。 */
|
||||
page: number;
|
||||
/** 当前页大小。 */
|
||||
page_size: number;
|
||||
/** 总页数。 */
|
||||
total_pages: number;
|
||||
/** 各触发类型规则数量。 */
|
||||
trigger_counts: Record<string, number>;
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
|
||||
/** 传统关键词列表项响应。 */
|
||||
/** 由当前 feature adapter 归一后的 KeywordBasicResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface KeywordBasicResponse {
|
||||
/** 匹配关键词。 */
|
||||
keyword: string;
|
||||
/** 文字回复内容。 */
|
||||
reply: string;
|
||||
}
|
||||
|
||||
/** 带商品范围的关键词列表项响应。 */
|
||||
/** 由当前 feature adapter 归一后的 KeywordItemResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface KeywordItemResponse extends KeywordBasicResponse {
|
||||
/** 限定的商品标识。 */
|
||||
item_id: string;
|
||||
}
|
||||
|
||||
/** 带类型和主键的关键词列表项响应。 */
|
||||
/** 由当前 feature adapter 归一后的 KeywordTypedResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface KeywordTypedResponse extends KeywordItemResponse {
|
||||
/** 关键词规则主键。 */
|
||||
id: number;
|
||||
/** 回复类型。 */
|
||||
type: 'text' | 'image';
|
||||
/** 图片回复地址。 */
|
||||
image_url: string;
|
||||
}
|
||||
|
||||
/** 指定商品回复项响应。 */
|
||||
/** 由当前 feature adapter 归一后的 ItemReplyResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface ItemReplyResponse {
|
||||
/** 商品平台标识。 */
|
||||
item_id?: string;
|
||||
/** 账号稳定标识。 */
|
||||
cookie_id?: string;
|
||||
/** 指定商品的回复内容。 */
|
||||
reply_content: string;
|
||||
}
|
||||
|
||||
/** 默认回复查询响应。 */
|
||||
/** 由当前 feature adapter 归一后的 DefaultReplyResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface DefaultReplyResponse extends DefaultReply {
|
||||
/** 账号稳定标识。 */
|
||||
cookie_id: string;
|
||||
}
|
||||
|
||||
// AutomationIssuesEnvelope 是自动化异常接口的兼容响应。
|
||||
/** 由当前 feature adapter 归一后的 AutomationIssuesEnvelope UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AutomationIssuesEnvelope {
|
||||
/** runs 是待处理的自动化运行记录。 */
|
||||
runs?: Array<{
|
||||
/** 记录标识。 */
|
||||
id: number;
|
||||
/** 所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 所属订单标识。 */
|
||||
order_id: string;
|
||||
/** 自动化触发类型。 */
|
||||
trigger_type: string;
|
||||
/** 外部错误说明。 */
|
||||
error_message: string;
|
||||
/** 异常类别。 */
|
||||
issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed';
|
||||
/** 允许的处理动作。 */
|
||||
allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>;
|
||||
/** 当前动作游标。 */
|
||||
action_cursor: number;
|
||||
/** 已发送数量。 */
|
||||
sent_count: number;
|
||||
/** 更新时间。 */
|
||||
updated_at: string;
|
||||
}>;
|
||||
/** pending_tasks 是延迟自动化任务列表。 */
|
||||
pending_tasks?: Array<{
|
||||
/** 任务标识。 */
|
||||
id: number;
|
||||
/** 所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 自动化触发类型。 */
|
||||
trigger_type: string;
|
||||
/** 错误说明。 */
|
||||
error_message: string;
|
||||
/** 当前重试次数。 */
|
||||
attempt_count: number;
|
||||
/** 更新时间。 */
|
||||
updated_at: string;
|
||||
}>;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ Bot,
|
||||
CheckCircle2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
CircleDollarSign,
|
||||
Clock3,
|
||||
Edit,
|
||||
Layers3,
|
||||
@@ -25,7 +26,7 @@ import { useRulesData } from '../hooks';
|
||||
import { filterAutomationIssues } from '../issueState';
|
||||
import { useRuleActions } from '../ruleActions';
|
||||
import type { AutomationTriggerType,RulesProps,RulesTab } from '../types';
|
||||
import { accentClasses,accountLabel,actionSummary,buildReviewConfig,cardActionsForTrigger,statusPill,triggerMeta,triggerOrder } from '../utils';
|
||||
import { accentClasses,accountLabel,actionSummary,adjustPriceTarget,buildReviewConfig,cardActionsForTrigger,statusPill,triggerMeta,triggerOrder } from '../utils';
|
||||
|
||||
// Rules 是规则 feature 在旧页面目录下保留的兼容入口组件。
|
||||
const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHandled }) => {
|
||||
@@ -105,7 +106,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
editingAutomationRule, setEditingAutomationRule,
|
||||
editingReplyRule, setEditingReplyRule, defaultForm, setDefaultForm, selectedRuleItem, isMultiSpecRule, currentTrigger,
|
||||
currentMeta, reviewConfig, displayVariants, openAutomationRule, openNewAutomationRule, handleTriggerChange,
|
||||
handleAutomationItemChange, updateVariant, appendDeliveryContent, handleSaveAutomationRule, handleDeleteAutomation,
|
||||
handleAutomationItemChange, updateVariant, updateAdjustPriceTarget, updateAdjustPriceNotifyText, appendDeliveryContent, handleSaveAutomationRule, handleDeleteAutomation,
|
||||
handleToggleAutomation, handleResolveRunIssue, handleResolveDeferredIssue, handleAddReplyRule, handleSaveReplyRule,
|
||||
handleDeleteReply, openDefaultReplyModal, handleSaveDefaultReply, handleDeleteDefaultReply, handleClearDefaultReplyRecords,
|
||||
} = ruleActions;
|
||||
@@ -722,7 +723,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedRuleItem && currentTrigger !== 'review_missing_timeout' && (
|
||||
{selectedRuleItem && currentTrigger !== 'review_missing_timeout' && currentTrigger !== 'order_created' && (
|
||||
<div className="mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4">
|
||||
<div className="flex flex-wrap items-center gap-2 mb-2">
|
||||
<span className="px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold">{selectedRuleItem.item_title || selectedRuleItem.item_id}</span>
|
||||
@@ -738,7 +739,43 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
)}
|
||||
</section>
|
||||
|
||||
{currentTrigger !== 'review_missing_timeout' ? (
|
||||
{currentTrigger === 'order_created' ? (
|
||||
<section className="bg-white rounded-3xl border border-gray-100 p-5">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<CircleDollarSign className="w-5 h-5 text-violet-600" />
|
||||
<h4 className="font-black text-gray-900">改价设置</h4>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">目标价格(元)</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
value={adjustPriceTarget(editingAutomationRule.actions)}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => updateAdjustPriceTarget(event.target.value)}
|
||||
placeholder="例如:9.9"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-2">买家拍下未付款后,系统会把该笔订单价格修改为此金额(0.01 - 1000000 元,最多两位小数)。</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">改价后提醒买家(可选)</label>
|
||||
<textarea
|
||||
value={editingAutomationRule.actions?.find(/* 当前回调处理集合中的单个元素。 */ action => action.action_type === 'send_text')?.message_template || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => updateAdjustPriceNotifyText(event.target.value)}
|
||||
placeholder="例如:已为您改好价格,请尽快支付哦~"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-24 resize-none"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-2">留空则只改价不发送消息。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 rounded-2xl bg-violet-50 border border-violet-100 p-4">
|
||||
<p className="text-xs leading-5 text-violet-700">
|
||||
改价仅对买家尚未付款的订单生效;订单已付款、已关闭或平台限制改价时任务会记录失败原因。建议配合商品说明引导买家「先拍下再等改价」。
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
) : currentTrigger !== 'review_missing_timeout' ? (
|
||||
<section className="bg-white rounded-3xl border border-gray-100 p-5">
|
||||
<div className="flex items-start justify-between gap-4 mb-4">
|
||||
<div>
|
||||
@@ -798,7 +835,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
className="w-full ios-input px-3 py-2.5 rounded-lg"
|
||||
>
|
||||
<option value="">请选择卡密库存</option>
|
||||
{cards.filter(/* 当前回调处理集合中的单个元素。 */ card => card.enabled && card.type !== 'api').map(/* 当前回调处理集合中的单个元素。 */ card => (
|
||||
{cards.filter(/* 当前回调处理集合中的单个元素。 */ card => card.enabled && (card.type !== 'api' || card.api_config?.ready === true)).map(/* 当前回调处理集合中的单个元素。 */ card => (
|
||||
<option key={card.id} value={card.id}>{card.name}</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -110,6 +110,44 @@ describe('useRuleActions', /* 当前回调验证规则页面动作协调器的
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('拍下改价规则校验目标价格并剔除空提醒动作', /* 当前回调验证拍下改价草稿与保存边界。 */ async () => {
|
||||
// hook 是规则动作 Hook 的真实 React 状态实例。
|
||||
const hook = renderHook(() => useRuleActionsHarness());
|
||||
act(/* 当前回调打开拍下改价规则弹窗。 */ () => hook.result.current.openNewAutomationRule('order_created'));
|
||||
expect(hook.result.current.editingAutomationRule?.variants).toEqual([]);
|
||||
|
||||
// 目标价格为空时保存被拒绝且不触达接口。
|
||||
await act(/* 当前回调执行空价格保存。 */ async () => hook.result.current.handleSaveAutomationRule());
|
||||
expect(updateShippingMock).not.toHaveBeenCalled();
|
||||
|
||||
act(/* 当前回调写入合法目标价格。 */ () => hook.result.current.updateAdjustPriceTarget('9.9'));
|
||||
act(/* 当前回调写入空白提醒文案。 */ () => hook.result.current.updateAdjustPriceNotifyText(' '));
|
||||
await act(/* 当前回调执行拍下改价保存。 */ async () => hook.result.current.handleSaveAutomationRule());
|
||||
expect(updateShippingMock).toHaveBeenCalledWith(expect.objectContaining({
|
||||
trigger_type: 'order_created',
|
||||
variants: [],
|
||||
actions: [expect.objectContaining({ action_type: 'adjust_price', config_json: '{"target_price":"9.9"}' })],
|
||||
}));
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('拍下改价规则保存带文案的可选提醒动作', /* 当前回调验证改价提醒文案的保存。 */ async () => {
|
||||
// hook 是规则动作 Hook 的真实 React 状态实例。
|
||||
const hook = renderHook(() => useRuleActionsHarness());
|
||||
act(/* 当前回调打开拍下改价规则弹窗。 */ () => hook.result.current.openNewAutomationRule('order_created'));
|
||||
act(/* 当前回调写入合法目标价格。 */ () => hook.result.current.updateAdjustPriceTarget('12'));
|
||||
act(/* 当前回调写入买家提醒文案。 */ () => hook.result.current.updateAdjustPriceNotifyText('已改价,请支付'));
|
||||
await act(/* 当前回调执行拍下改价保存。 */ async () => hook.result.current.handleSaveAutomationRule());
|
||||
expect(updateShippingMock).toHaveBeenCalledWith(expect.objectContaining({
|
||||
trigger_type: 'order_created',
|
||||
actions: [
|
||||
expect.objectContaining({ action_type: 'adjust_price', config_json: '{"target_price":"12"}' }),
|
||||
expect.objectContaining({ action_type: 'send_text', message_template: '已改价,请支付' }),
|
||||
],
|
||||
}));
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('关键词和默认回复动作分别读取、保存并刷新', /* 当前回调验证两个回复页签的动作边界。 */ async () => {
|
||||
// hook 是规则动作 Hook 的真实 React 状态实例。
|
||||
const hook = renderHook(() => useRuleActionsHarness());
|
||||
|
||||
@@ -16,7 +16,7 @@ updateShippingRule,
|
||||
} from './api';
|
||||
import { finishRuleSubmission,idleRuleSubmitState,startRuleSubmission,type RuleSubmitState } from './interactionState';
|
||||
import type { AutomationTriggerType,Card,DefaultReplyForm,Item,ReplyRule,RulesProps,RulesTab,ShippingRule,ShippingVariant } from './types';
|
||||
import { boolFlag,buildReviewConfig,cardActionsForTrigger,defaultRuleName,emptyVariant,parseJSONObject,shouldReplaceGeneratedName,triggerMeta } from './utils';
|
||||
import { adjustPriceTarget,boolFlag,buildAdjustPriceConfig,buildReviewConfig,cardActionsForTrigger,defaultRuleName,emptyVariant,isValidAdjustPrice,parseJSONObject,shouldReplaceGeneratedName,triggerMeta } from './utils';
|
||||
|
||||
// RuleActionsOptions 描述规则动作协调器依赖的页面数据、刷新函数和外部联动目标。
|
||||
export interface RuleActionsOptions {
|
||||
@@ -106,6 +106,10 @@ export interface RuleActionsState {
|
||||
handleAutomationItemChange: (itemID: string) => void;
|
||||
// updateVariant 更新指定发货规格的字段。
|
||||
updateVariant: (index: number, patch: Partial<ShippingVariant>) => void;
|
||||
// updateAdjustPriceTarget 更新拍下改价草稿的目标价格。
|
||||
updateAdjustPriceTarget: (targetPrice: string) => void;
|
||||
// updateAdjustPriceNotifyText 更新拍下改价草稿的可选买家提醒文案。
|
||||
updateAdjustPriceNotifyText: (text: string) => void;
|
||||
// appendDeliveryContent 追加一行发货规格。
|
||||
appendDeliveryContent: () => void;
|
||||
// handleSaveAutomationRule 保存当前自动化规则。
|
||||
@@ -198,7 +202,7 @@ export const useRuleActions = ({
|
||||
name: defaultRuleName(trigger, itemLabel), trigger_type: trigger, cookie_id: cookieID, item_id: itemID,
|
||||
item_title: item?.item_title || '', item_keyword: itemLabel, card_group_id: 0, priority: 100, enabled: true,
|
||||
config_json: trigger === 'review_missing_timeout' ? buildReviewConfig() : '{}', actions: cardActionsForTrigger(trigger),
|
||||
variants: trigger === 'review_missing_timeout' ? [] : [emptyVariant()],
|
||||
variants: trigger === 'review_missing_timeout' || trigger === 'order_created' ? [] : [emptyVariant()],
|
||||
};
|
||||
}, [items, selectedAccountId]);
|
||||
|
||||
@@ -211,7 +215,7 @@ export const useRuleActions = ({
|
||||
trigger_type: trigger,
|
||||
config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(rule.config_json) : (rule.config_json || '{}'),
|
||||
actions: rule.actions?.length ? rule.actions.map(/* 当前回调复制自动化动作。 */ action => ({ ...action })) : cardActionsForTrigger(trigger, rule.card_group_id),
|
||||
variants: rule.variants?.length ? rule.variants.map(/* 当前回调复制发货规格。 */ variant => ({ ...variant })) : (trigger === 'review_missing_timeout' ? [] : [emptyVariant()]),
|
||||
variants: rule.variants?.length ? rule.variants.map(/* 当前回调复制发货规格。 */ variant => ({ ...variant })) : (trigger === 'review_missing_timeout' || trigger === 'order_created' ? [] : [emptyVariant()]),
|
||||
});
|
||||
setShowAutomationModal(true);
|
||||
}, []);
|
||||
@@ -288,7 +292,7 @@ export const useRuleActions = ({
|
||||
name: shouldReplaceGeneratedName(editingAutomationRule.name) ? defaultRuleName(trigger, itemLabel) : editingAutomationRule.name,
|
||||
card_group_id: currentCardID, config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(editingAutomationRule.config_json) : '{}',
|
||||
actions: cardActionsForTrigger(trigger, currentCardID),
|
||||
variants: trigger === 'review_missing_timeout' ? [] : (editingAutomationRule.variants?.length ? editingAutomationRule.variants : [{ ...emptyVariant(), card_id: currentCardID }]),
|
||||
variants: trigger === 'review_missing_timeout' || trigger === 'order_created' ? [] : (editingAutomationRule.variants?.length ? editingAutomationRule.variants : [{ ...emptyVariant(), card_id: currentCardID }]),
|
||||
});
|
||||
}, [editingAutomationRule, selectedRuleItem]);
|
||||
|
||||
@@ -313,6 +317,35 @@ export const useRuleActions = ({
|
||||
setEditingAutomationRule({ ...editingAutomationRule, variants: next, card_group_id: next[0]?.card_id || 0 });
|
||||
}, [displayVariants, editingAutomationRule]);
|
||||
|
||||
// updateAdjustPriceTarget 更新拍下改价草稿中的目标价格。
|
||||
const updateAdjustPriceTarget = useCallback(/* adjustPriceAction 更新改价目标价格。 */ (targetPrice: string) => {
|
||||
if (!editingAutomationRule) return;
|
||||
// baseActions 保存至少包含改价动作的当前动作列表。
|
||||
const baseActions = editingAutomationRule.actions?.some(/* 当前回调查找改价动作。 */ action => action.action_type === 'adjust_price')
|
||||
? editingAutomationRule.actions
|
||||
: cardActionsForTrigger('order_created');
|
||||
setEditingAutomationRule({
|
||||
...editingAutomationRule,
|
||||
actions: baseActions.map(/* 当前回调把新目标价格写入改价动作配置。 */ action =>
|
||||
action.action_type === 'adjust_price' ? { ...action, config_json: buildAdjustPriceConfig(targetPrice) } : action),
|
||||
});
|
||||
}, [editingAutomationRule]);
|
||||
|
||||
// updateAdjustPriceNotifyText 更新拍下改价草稿中的可选买家提醒文案。
|
||||
const updateAdjustPriceNotifyText = useCallback(/* adjustNotifyAction 更新改价提醒文案。 */ (text: string) => {
|
||||
if (!editingAutomationRule) return;
|
||||
// actions 保存当前动作列表副本。
|
||||
const actions = (editingAutomationRule.actions || []).slice();
|
||||
// textIndex 是可选提醒动作在列表中的位置。
|
||||
const textIndex = actions.findIndex(/* 当前回调查找提醒文案动作。 */ action => action.action_type === 'send_text');
|
||||
if (textIndex >= 0) {
|
||||
actions[textIndex] = { ...actions[textIndex], message_template: text };
|
||||
} else {
|
||||
actions.push({ action_type: 'send_text', message_template: text, enabled: true, sort_order: actions.length + 1 });
|
||||
}
|
||||
setEditingAutomationRule({ ...editingAutomationRule, actions });
|
||||
}, [editingAutomationRule]);
|
||||
|
||||
// appendDeliveryContent 在规格编辑器末尾追加一行。
|
||||
const appendDeliveryContent = useCallback(/* appendVariantAction 追加规则规格。 */ () => {
|
||||
if (!editingAutomationRule) return;
|
||||
@@ -332,7 +365,7 @@ export const useRuleActions = ({
|
||||
if (!editingAutomationRule.cookie_id) return alert('请选择账号');
|
||||
// variants 保存当前规格列表。
|
||||
const variants = editingAutomationRule.variants?.length ? editingAutomationRule.variants : [];
|
||||
if (trigger !== 'review_missing_timeout') {
|
||||
if (trigger !== 'review_missing_timeout' && trigger !== 'order_created') {
|
||||
if (!variants.length || variants.some(/* 当前回调校验卡密组是否已选择。 */ variant => !variant.card_id)) return alert(trigger === 'buyer_reviewed' ? '请选择评价赠品卡密库存' : '请选择发货卡密库存');
|
||||
if (isMultiSpecRule && variants.some(/* 当前回调校验多规格字段。 */ variant => !variant.spec_name.trim() || !variant.spec_value.trim())) return alert('多规格商品必须填写每一行的规格名称和规格值');
|
||||
}
|
||||
@@ -341,13 +374,19 @@ export const useRuleActions = ({
|
||||
const text = editingAutomationRule.actions?.find(/* 当前回调查找求评价文案动作。 */ action => action.action_type === 'send_text')?.message_template || '';
|
||||
if (!text.trim()) return alert('请填写求评价文案');
|
||||
}
|
||||
// saveActions 保存实际提交的动作列表;拍下改价规则会剔除未填写文案的可选提醒动作。
|
||||
let saveActions = editingAutomationRule.actions?.length ? editingAutomationRule.actions : cardActionsForTrigger(trigger, editingAutomationRule.card_group_id || 0);
|
||||
if (trigger === 'order_created') {
|
||||
if (!isValidAdjustPrice(adjustPriceTarget(saveActions))) return alert('请填写 0.01 到 1000000 元、最多两位小数的目标价格');
|
||||
saveActions = saveActions.filter(/* 当前回调剔除空文案的可选提醒动作。 */ action => action.action_type !== 'send_text' || Boolean(action.message_template?.trim()));
|
||||
}
|
||||
// saveVariants 保存归一化后的发货规格。
|
||||
const saveVariants = trigger === 'review_missing_timeout' ? [] : variants.map(/* 当前回调归一化发货规格字段。 */ variant => ({ ...variant, spec_name: isMultiSpecRule ? variant.spec_name.trim() : '', spec_value: isMultiSpecRule ? variant.spec_value.trim() : '', delivery_count: Math.max(1, Number(variant.delivery_count) || 1), enabled: variant.enabled !== false }));
|
||||
const saveVariants = trigger === 'review_missing_timeout' || trigger === 'order_created' ? [] : variants.map(/* 当前回调归一化发货规格字段。 */ variant => ({ ...variant, spec_name: isMultiSpecRule ? variant.spec_name.trim() : '', spec_value: isMultiSpecRule ? variant.spec_value.trim() : '', delivery_count: Math.max(1, Number(variant.delivery_count) || 1), enabled: variant.enabled !== false }));
|
||||
setAutomationSubmitState(startRuleSubmission(automationSubmitState));
|
||||
// succeeded 记录保存是否成功。
|
||||
let succeeded = false;
|
||||
try {
|
||||
await updateShippingRule({ ...editingAutomationRule, trigger_type: trigger, name: (editingAutomationRule.name || '').trim() || defaultRuleName(trigger, selectedRuleItem?.item_title || editingAutomationRule.item_id || ''), config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(editingAutomationRule.config_json) : (editingAutomationRule.config_json || '{}'), actions: editingAutomationRule.actions?.length ? editingAutomationRule.actions : cardActionsForTrigger(trigger, saveVariants[0]?.card_id || editingAutomationRule.card_group_id || 0), variants: saveVariants });
|
||||
await updateShippingRule({ ...editingAutomationRule, trigger_type: trigger, name: (editingAutomationRule.name || '').trim() || defaultRuleName(trigger, selectedRuleItem?.item_title || editingAutomationRule.item_id || ''), config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(editingAutomationRule.config_json) : (editingAutomationRule.config_json || '{}'), actions: trigger === 'order_created' ? saveActions : (editingAutomationRule.actions?.length ? editingAutomationRule.actions : cardActionsForTrigger(trigger, saveVariants[0]?.card_id || editingAutomationRule.card_group_id || 0)), variants: saveVariants });
|
||||
setShowAutomationModal(false);
|
||||
await Promise.all([loadAutomationRules(), loadReferenceData()]);
|
||||
alert('保存成功');
|
||||
@@ -451,7 +490,7 @@ export const useRuleActions = ({
|
||||
automationSubmitState, replySubmitState, defaultReplySubmitState, editingAutomationRule, setEditingAutomationRule,
|
||||
editingReplyRule, setEditingReplyRule, defaultForm, setDefaultForm, selectedRuleItem, isMultiSpecRule, currentTrigger,
|
||||
currentMeta, reviewConfig, displayVariants, buildAutomationDraft, openAutomationRule, openNewAutomationRule,
|
||||
handleTriggerChange, handleAutomationItemChange, updateVariant, appendDeliveryContent, handleSaveAutomationRule,
|
||||
handleTriggerChange, handleAutomationItemChange, updateVariant, updateAdjustPriceTarget, updateAdjustPriceNotifyText, appendDeliveryContent, handleSaveAutomationRule,
|
||||
handleDeleteAutomation, handleToggleAutomation, handleResolveRunIssue, handleResolveDeferredIssue, handleAddReplyRule,
|
||||
handleSaveReplyRule, handleDeleteReply, openDefaultReplyModal, handleSaveDefaultReply, handleDeleteDefaultReply,
|
||||
handleClearDefaultReplyRecords,
|
||||
|
||||
@@ -68,7 +68,7 @@ export interface TriggerMeta {
|
||||
// flow 是该触发类型的步骤摘要。
|
||||
flow: string[];
|
||||
// accent 是页面使用的主题色名称。
|
||||
accent: 'blue' | 'emerald' | 'amber';
|
||||
accent: 'blue' | 'emerald' | 'amber' | 'violet';
|
||||
// icon 是触发类型对应的图标组件。
|
||||
icon: ElementType;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import type { AccountDetail,ShippingRule } from '../../../shared/api-contract/automation';
|
||||
import type { AccountDetail,ShippingRule } from './api';
|
||||
import {
|
||||
accentClasses,
|
||||
accountLabel,
|
||||
actionSummary,
|
||||
adjustPriceTarget,
|
||||
boolFlag,
|
||||
buildAdjustPriceConfig,
|
||||
buildReviewConfig,
|
||||
cardActionsForTrigger,
|
||||
defaultRuleName,
|
||||
emptyVariant,
|
||||
isValidAdjustPrice,
|
||||
parseJSONObject,
|
||||
shouldReplaceGeneratedName,
|
||||
statusPill,
|
||||
@@ -49,10 +52,13 @@ describe('规则工具函数', /* 当前回调处理规则配置和展示状态
|
||||
expect(shouldReplaceGeneratedName('我自定义的规则')).toBe(false);
|
||||
});
|
||||
|
||||
test('创建三类触发器的默认动作链', /* 当前回调处理规则配置和展示状态。 */ () => {
|
||||
test('创建各类触发器的默认动作链', /* 当前回调处理规则配置和展示状态。 */ () => {
|
||||
expect(cardActionsForTrigger('review_missing_timeout')).toEqual([{
|
||||
action_type: 'send_text', message_template: '亲,商品使用满意的话,麻烦给个评价,谢谢~', enabled: true, sort_order: 1,
|
||||
}]);
|
||||
expect(cardActionsForTrigger('order_created')).toEqual([{
|
||||
action_type: 'adjust_price', config_json: '{"target_price":""}', enabled: true, sort_order: 1,
|
||||
}]);
|
||||
expect(cardActionsForTrigger('order_paid', 7)).toEqual([
|
||||
{ action_type: 'send_card', card_id: 7, delivery_count: 1, enabled: true, sort_order: 1 },
|
||||
{ action_type: 'confirm_shipment', enabled: true, sort_order: 2 },
|
||||
@@ -62,6 +68,23 @@ describe('规则工具函数', /* 当前回调处理规则配置和展示状态
|
||||
]);
|
||||
});
|
||||
|
||||
test('校验并读取拍下改价的目标价格', /* 当前回调处理规则配置和展示状态。 */ () => {
|
||||
expect(buildAdjustPriceConfig(' 9.9 ')).toBe('{"target_price":"9.9"}');
|
||||
expect(adjustPriceTarget([{ action_type: 'adjust_price', config_json: '{"target_price":"12.5"}', enabled: true }])).toBe('12.5');
|
||||
expect(adjustPriceTarget([{ action_type: 'send_text', message_template: 'x', enabled: true }])).toBe('');
|
||||
expect(adjustPriceTarget()).toBe('');
|
||||
expect(isValidAdjustPrice('9.9')).toBe(true);
|
||||
expect(isValidAdjustPrice('0.01')).toBe(true);
|
||||
expect(isValidAdjustPrice('1000000')).toBe(true);
|
||||
expect(isValidAdjustPrice('0')).toBe(false);
|
||||
expect(isValidAdjustPrice('')).toBe(false);
|
||||
expect(isValidAdjustPrice('1.234')).toBe(false);
|
||||
expect(isValidAdjustPrice('abc')).toBe(false);
|
||||
expect(isValidAdjustPrice('1000000.01')).toBe(false);
|
||||
expect(actionSummary(rule({ trigger_type: 'order_created', actions: [{ action_type: 'adjust_price', config_json: '{"target_price":"9.9"}', enabled: true }] }))).toBe('拍下后改价为 ¥9.9');
|
||||
expect(actionSummary(rule({ trigger_type: 'order_created', actions: [] }))).toBe('未配置目标价格');
|
||||
});
|
||||
|
||||
test('汇总动作、主题样式和布尔标志', /* 当前回调处理规则配置和展示状态。 */ () => {
|
||||
expect(actionSummary(rule({ trigger_type: 'review_missing_timeout', actions: [{ action_type: 'send_text', message_template: '请评价', enabled: true }] }))).toBe('请评价');
|
||||
expect(actionSummary(rule({ trigger_type: 'review_missing_timeout', actions: [] }))).toBe('发送求评价文案');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Clock3,Gift,PackageCheck } from 'lucide-react';
|
||||
import { CircleDollarSign,Clock3,Gift,PackageCheck } from 'lucide-react';
|
||||
import type {
|
||||
AccountDetail,
|
||||
AutomationAction,
|
||||
@@ -10,6 +10,14 @@ import type { TriggerMeta } from './types';
|
||||
|
||||
// triggerMeta 是自动化触发类型的统一展示元数据,供列表和编辑器复用。
|
||||
export const triggerMeta: Record<AutomationTriggerType, TriggerMeta> = {
|
||||
order_created: {
|
||||
label: '拍下未付款自动改价',
|
||||
shortLabel: '拍下改价',
|
||||
description: '买家拍下商品未付款时,把该笔待付款订单的价格自动修改为目标价格。',
|
||||
flow: ['拍下待付款卡片', '匹配商品规则', '修改订单价格', '可选提醒买家'],
|
||||
accent: 'violet',
|
||||
icon: CircleDollarSign,
|
||||
},
|
||||
order_paid: {
|
||||
label: '付款后自动发货',
|
||||
shortLabel: '自动发货',
|
||||
@@ -37,7 +45,7 @@ export const triggerMeta: Record<AutomationTriggerType, TriggerMeta> = {
|
||||
};
|
||||
|
||||
// triggerOrder 固定自动化类型在创建面板和筛选器中的排序。
|
||||
export const triggerOrder: AutomationTriggerType[] = ['order_paid', 'buyer_reviewed', 'review_missing_timeout'];
|
||||
export const triggerOrder: AutomationTriggerType[] = ['order_paid', 'order_created', 'buyer_reviewed', 'review_missing_timeout'];
|
||||
|
||||
// reviewRequestText 是超时未评价规则的默认提醒文案。
|
||||
export const reviewRequestText = '亲,商品使用满意的话,麻烦给个评价,谢谢~';
|
||||
@@ -95,8 +103,39 @@ export const shouldReplaceGeneratedName = (name?: string) => {
|
||||
);
|
||||
};
|
||||
|
||||
// buildAdjustPriceConfig 把目标价格文本序列化为改价动作配置 JSON。
|
||||
export const buildAdjustPriceConfig = (targetPrice: string) => JSON.stringify({ target_price: targetPrice.trim() });
|
||||
|
||||
// adjustPriceTarget 从动作列表读取改价动作的目标价格文本。
|
||||
export const adjustPriceTarget = (actions?: AutomationAction[]): string => {
|
||||
// action 是动作列表中的改价动作。
|
||||
const action = (actions || []).find(
|
||||
// 改价动作匹配器只查找订单改价类型。
|
||||
candidate => candidate.action_type === 'adjust_price',
|
||||
);
|
||||
return String(parseJSONObject(action?.config_json).target_price ?? '');
|
||||
};
|
||||
|
||||
// isValidAdjustPrice 校验目标价格是否为 0.01 到 1000000 元、最多两位小数的金额。
|
||||
export const isValidAdjustPrice = (raw: string): boolean => {
|
||||
// trimmed 是去掉首尾空白后的金额文本。
|
||||
const trimmed = raw.trim();
|
||||
if (!/^\d+(\.\d{1,2})?$/.test(trimmed)) return false;
|
||||
// cents 是金额折算出的整数分。
|
||||
const cents = Math.round(Number(trimmed) * 100);
|
||||
return cents >= 1 && cents <= 100000000;
|
||||
};
|
||||
|
||||
// cardActionsForTrigger 根据触发类型创建默认动作链。
|
||||
export const cardActionsForTrigger = (trigger: AutomationTriggerType, cardID = 0): AutomationAction[] => {
|
||||
if (trigger === 'order_created') {
|
||||
return [{
|
||||
action_type: 'adjust_price',
|
||||
config_json: buildAdjustPriceConfig(''),
|
||||
enabled: true,
|
||||
sort_order: 1,
|
||||
}];
|
||||
}
|
||||
if (trigger === 'review_missing_timeout') {
|
||||
return [{
|
||||
action_type: 'send_text',
|
||||
@@ -123,6 +162,11 @@ export const cardActionsForTrigger = (trigger: AutomationTriggerType, cardID = 0
|
||||
|
||||
// actionSummary 将规则动作转换成列表中的简短摘要。
|
||||
export const actionSummary = (rule: ShippingRule) => {
|
||||
if (rule.trigger_type === 'order_created') {
|
||||
// target 是规则配置的改价目标价格。
|
||||
const target = adjustPriceTarget(rule.actions);
|
||||
return target ? `拍下后改价为 ¥${target}` : '未配置目标价格';
|
||||
}
|
||||
if (rule.trigger_type === 'review_missing_timeout') {
|
||||
return rule.actions?.find(
|
||||
// 文案动作匹配器只查找发送文字动作。
|
||||
@@ -148,6 +192,7 @@ export const accentClasses = (accent: TriggerMeta['accent'], selected = false) =
|
||||
blue: selected ? 'border-blue-500 bg-blue-50 text-blue-700' : 'border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300',
|
||||
emerald: selected ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300',
|
||||
amber: selected ? 'border-amber-500 bg-amber-50 text-amber-700' : 'border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300',
|
||||
violet: selected ? 'border-violet-500 bg-violet-50 text-violet-700' : 'border-violet-100 bg-violet-50/60 text-violet-700 hover:border-violet-300',
|
||||
};
|
||||
return map[accent] || map.blue;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { OperationResponse,SessionResponse } from '../../../shared/api-contract/session';
|
||||
import { get,post,type RequestControlOptions } from '../../../shared/http/client';
|
||||
export type * from '../../../shared/api-contract/session';
|
||||
import type { OperationResponse,SessionResponse } from './models';
|
||||
import { contractClient, runContractRequest, type ContractRequestOptions } from '../../../shared/api-contract/client';
|
||||
export type * from './models';
|
||||
|
||||
/** 会话状态接口返回的只读传输契约。 */
|
||||
export interface SessionStatusResponse {
|
||||
@@ -29,13 +29,32 @@ export interface LoginRequest {
|
||||
}
|
||||
|
||||
/** 以用户名密码或邮箱验证码建立管理会话。 */
|
||||
export const login = async (data: LoginRequest): Promise<SessionResponse> => post('/api/v1/session/login', data, { skipAuthLogout: true });
|
||||
export const login = async (data: LoginRequest): Promise<SessionResponse> => {
|
||||
// response 是生成契约校验后的登录成功响应。
|
||||
const response = await runContractRequest(
|
||||
/* signal 是本次登录请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/session/login', { body: data, signal }),
|
||||
{ skipAuthLogout: true },
|
||||
);
|
||||
return { ...response, token: response.token ?? undefined };
|
||||
};
|
||||
|
||||
/** 用首次设置的管理员密码完成系统初始化并建立会话。 */
|
||||
export const initializeAdmin = async (password: string): Promise<SessionResponse> => post('/api/v1/session/initialize', { password }, { skipAuthLogout: true });
|
||||
export const initializeAdmin = async (password: string): Promise<SessionResponse> => {
|
||||
// response 是生成契约校验后的首次初始化成功响应。
|
||||
const response = await runContractRequest(
|
||||
/* signal 是本次初始化请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/session/initialize', { body: { password }, signal }),
|
||||
{ skipAuthLogout: true },
|
||||
);
|
||||
return { ...response, token: response.token ?? undefined };
|
||||
};
|
||||
|
||||
/** 读取当前浏览器的认证与初始化状态,调用者可取消页面卸载前的请求。 */
|
||||
export const verifySession = async (options?: RequestControlOptions): Promise<SessionStatusResponse> => get('/api/v1/session', undefined, options);
|
||||
export const verifySession = async (options?: ContractRequestOptions): Promise<SessionStatusResponse> =>
|
||||
runContractRequest(/* signal 是本次会话校验请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/session', { signal }), options);
|
||||
|
||||
/** 结束当前浏览器会话。 */
|
||||
export const logout = async (): Promise<OperationResponse> => post('/api/v1/session/logout', {});
|
||||
export const logout = async (): Promise<OperationResponse> => {
|
||||
// response 是注销接口仅返回的用户可见提示。
|
||||
const response = await runContractRequest(/* signal 是本次注销请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/session/logout', { body: {}, signal }));
|
||||
return { success: true, message: response.message };
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 SessionResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface SessionResponse {
|
||||
/** 表示登录或初始化是否成功。 */
|
||||
success: boolean;
|
||||
/** 登录成功后的会话 Token。 */
|
||||
token?: string;
|
||||
/** 服务端返回的操作说明。 */
|
||||
message?: string;
|
||||
/** 当前用户 ID。 */
|
||||
user_id?: number;
|
||||
/** 当前用户名。 */
|
||||
username?: string;
|
||||
/** 当前用户是否为管理员。 */
|
||||
is_admin?: boolean;
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { AIModelsResponse,OperationResponse,SystemSettings } from '../../../shared/api-contract/settings';
|
||||
import { get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
export type * from '../../../shared/api-contract/settings';
|
||||
import type { OperationResponse,SystemSettings } from './models';
|
||||
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { normalizeSystemSettingsUpdate,SENSITIVE_SYSTEM_SETTING_KEYS } from '../../../shared/api-contract/settings';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import type { SystemSettingsUpdate } from '../../../shared/api-contract/settings';
|
||||
export type * from './models';
|
||||
export { normalizeSystemSettingsUpdate } from '../../../shared/api-contract/settings';
|
||||
export type { SensitiveSettingChange,SystemSettingsUpdate } from '../../../shared/api-contract/settings';
|
||||
|
||||
/** 设置页面使用的会话状态传输契约,避免跨 feature 依赖。 */
|
||||
export interface SettingsSessionStatusResponse {
|
||||
@@ -16,43 +21,6 @@ export interface SettingsSessionStatusResponse {
|
||||
is_admin?: boolean;
|
||||
}
|
||||
|
||||
/** 敏感系统设置的显式三态变更命令。 */
|
||||
export type SensitiveSettingChange = {
|
||||
/** 敏感值的保存策略。 */
|
||||
action: 'retain' | 'replace' | 'clear';
|
||||
/** replace 策略需要保存的新值,只存在于提交请求中。 */
|
||||
value?: string;
|
||||
};
|
||||
|
||||
/** 系统设置更新请求,将普通配置与敏感命令分开传输。 */
|
||||
export type SystemSettingsUpdate = {
|
||||
/** 非敏感配置字段。 */
|
||||
values?: Record<string, unknown>;
|
||||
/** 由服务端解释的敏感值变更命令。 */
|
||||
secrets?: Record<string, SensitiveSettingChange>;
|
||||
};
|
||||
|
||||
/** SENSITIVE_SYSTEM_SETTING_KEYS 标识不得写入普通 values 的秘密键。 */
|
||||
const SENSITIVE_SYSTEM_SETTING_KEYS = new Set(['ai_api_key', 'smtp_password', 'qq_reply_secret_key', 'captcha.remote_secret_key']);
|
||||
|
||||
/** 将历史设置草稿转换为服务端要求的普通值与敏感命令结构。 */
|
||||
const normalizeSystemSettingsUpdate = (settings: Partial<SystemSettings> | SystemSettingsUpdate): Record<string, unknown> => {
|
||||
if ('values' in settings || 'secrets' in settings) return settings;
|
||||
// values 保存普通设置,永不容纳秘密文本。
|
||||
const values: Record<string, unknown> = {};
|
||||
// secrets 保存服务端需要独立处理的敏感设置命令。
|
||||
const secrets: Record<string, SensitiveSettingChange> = {};
|
||||
for (const /* key、value 是当前待分流的设置键和值。 */ [key, value] of Object.entries(settings)) {
|
||||
if (value === undefined || value === null) continue;
|
||||
if (SENSITIVE_SYSTEM_SETTING_KEYS.has(key)) {
|
||||
secrets[key] = value === '' ? { action: 'clear' } : { action: 'replace', value: String(value) };
|
||||
continue;
|
||||
}
|
||||
values[key] = value;
|
||||
}
|
||||
return Object.keys(secrets).length > 0 ? { values, secrets } : values;
|
||||
};
|
||||
|
||||
/** 将服务端可兼容的字符串和数值设置归一为 UI 可消费的只读契约。 */
|
||||
const normalizeSettings = (settings: Record<string, unknown>): SystemSettings => {
|
||||
// result 是不修改原始响应的设置副本。
|
||||
@@ -68,33 +36,45 @@ const normalizeSettings = (settings: Record<string, unknown>): SystemSettings =>
|
||||
const days = Number(result.renewal_log_retention_days);
|
||||
result.renewal_log_retention_days = Number.isFinite(days) ? days : 10;
|
||||
}
|
||||
if ('outbound_http_public_only' in result) {
|
||||
// publicOnly 保存统一出站策略的布尔状态,兼容旧服务端返回的字符串。
|
||||
result.outbound_http_public_only = result.outbound_http_public_only === true || result.outbound_http_public_only === 'true';
|
||||
}
|
||||
return result as SystemSettings;
|
||||
};
|
||||
|
||||
/** 修改当前管理员的密码。 */
|
||||
export const changePassword = async (currentPassword: string, newPassword: string): Promise<OperationResponse> => post('/api/v1/session/password', { current_password: currentPassword, new_password: newPassword });
|
||||
export const changePassword = async (currentPassword: string, newPassword: string): Promise<OperationResponse> =>
|
||||
runContractRequest(/* signal 是本次管理员密码更新请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/session/password', { body: { current_password: currentPassword, new_password: newPassword }, signal }));
|
||||
|
||||
/** 修改当前管理员的登录名称与可选密码。 */
|
||||
export const updateLoginCredentials = async (data: { /** 当前密码用于服务端重新验证身份。 */ current_password: string; /** 新的管理员名称。 */ new_username: string; /** 可选的新密码。 */ new_password?: string }, options?: RequestControlOptions): Promise<OperationResponse> => put('/api/v1/session/credentials', data, options);
|
||||
export const updateLoginCredentials = async (data: { /** 当前密码用于服务端重新验证身份。 */ current_password: string; /** 新的管理员名称。 */ new_username: string; /** 可选的新密码。 */ new_password?: string }, options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
runContractRequest(/* signal 是本次管理员凭据更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/session/credentials', { body: data, signal }), options);
|
||||
|
||||
/** 获取系统设置;仅保留敏感值是否已配置的状态,不接收敏感明文。 */
|
||||
export const getSystemSettings = async (options?: RequestControlOptions): Promise<SystemSettings> => {
|
||||
// response 是服务端可能包裹在 data 中的设置响应。
|
||||
const response = await get<{ /** settings 是当前系统配置对象。 */ data?: Record<string, unknown>; /** settings 是未包裹的兼容设置对象。 */ settings?: Record<string, unknown> } & Record<string, unknown>>('/api/v1/settings/system', undefined, options);
|
||||
// settings 是去除 transport 包裹后的配置对象。
|
||||
const settings = response.data || response.settings || response;
|
||||
return normalizeSettings(settings);
|
||||
// response 是 OpenAPI 约束的脱敏系统设置键值对象。
|
||||
const response = await runContractRequest(/* signal 是本次系统设置读取请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/settings/system', { signal }), options);
|
||||
return normalizeSettings(response);
|
||||
};
|
||||
|
||||
/** 保存普通系统配置和敏感设置命令。 */
|
||||
export const updateSystemSettings = async (settings: Partial<SystemSettings> | SystemSettingsUpdate, options?: RequestControlOptions): Promise<OperationResponse> => put('/api/v1/settings/system', normalizeSystemSettingsUpdate(settings), options);
|
||||
export const updateSystemSettings = async (settings: Partial<SystemSettings> | SystemSettingsUpdate, options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
runContractRequest(/* signal 是本次系统设置更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/settings/system', {
|
||||
body: normalizeSystemSettingsUpdate(settings),
|
||||
signal,
|
||||
}), options);
|
||||
|
||||
/** 向服务端请求指定人工智能服务的可用模型列表。 */
|
||||
export const fetchAIModels = async (baseURL: string, apiKey = '', options?: RequestControlOptions): Promise<string[]> => {
|
||||
// response 是模型发现接口的具名响应。
|
||||
const response = await post<AIModelsResponse>('/api/v1/settings/ai-models', { base_url: baseURL, api_key: apiKey }, options);
|
||||
const response = await runContractRequest(/* signal 是本次模型发现请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/settings/ai-models', {
|
||||
body: { base_url: baseURL, api_key: apiKey },
|
||||
signal,
|
||||
}), options);
|
||||
return Array.isArray(response.models) ? response.models : [];
|
||||
};
|
||||
|
||||
/** 在保存登录凭据前读取当前会话状态。 */
|
||||
export const verifySession = async (options?: RequestControlOptions): Promise<SettingsSessionStatusResponse> => get('/api/v1/session', undefined, options);
|
||||
export const verifySession = async (options?: RequestControlOptions): Promise<SettingsSessionStatusResponse> =>
|
||||
runContractRequest(/* signal 是本次设置页会话校验请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/session', { signal }), 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 { OperationResponse,SystemSettings } from '../../../shared/api-contract/settings';
|
||||
import type { OperationResponse,SystemSettings } from './api';
|
||||
import { fetchAIModels,getSystemSettings,updateLoginCredentials,updateSystemSettings,verifySession } from './api';
|
||||
import { useSettings } from './hooks';
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
|
||||
/** 由当前 feature adapter 归一后的 SystemSettings UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface SystemSettings {
|
||||
/** 默认 AI 模型名称。 */
|
||||
ai_model?: string;
|
||||
/** 全局 AI API 密钥。 */
|
||||
ai_api_key?: string;
|
||||
/** 全局 AI API 密钥是否已在服务端配置。 */
|
||||
ai_api_key_configured?: boolean;
|
||||
/** 全局 AI API 地址。 */
|
||||
ai_api_url?: string;
|
||||
/** 全局 AI 基础地址。 */
|
||||
ai_base_url?: string;
|
||||
/** 系统默认回复文案。 */
|
||||
default_reply?: string;
|
||||
/** 是否允许注册新用户。 */
|
||||
registration_enabled?: boolean;
|
||||
/** 系统 SMTP 服务器地址。 */
|
||||
smtp_server?: string;
|
||||
/** 系统 SMTP 密码是否已在服务端配置。 */
|
||||
smtp_password_configured?: boolean;
|
||||
/** 服务端日志级别。 */
|
||||
log_level?: 'debug' | 'info' | 'warn' | 'error' | string;
|
||||
/** 服务端日志格式。 */
|
||||
log_format?: 'text' | 'json' | string;
|
||||
/** 是否阻止用户配置的服务端 HTTP 请求访问内网地址。 */
|
||||
outbound_http_public_only?: boolean;
|
||||
/** 续期日志保留天数。 */
|
||||
renewal_log_retention_days?: number;
|
||||
/** 远程验证码服务地址。 */
|
||||
'captcha.remote_service_url'?: string;
|
||||
/** 远程验证码服务密钥。 */
|
||||
'captcha.remote_secret_key'?: string;
|
||||
/** 远程验证码服务密钥是否已在服务端配置。 */
|
||||
'captcha.remote_secret_key_configured'?: boolean;
|
||||
/** 远程验证码服务 Cookie 配置。 */
|
||||
'captcha.remote_pass_cookies'?: boolean | string;
|
||||
/** 兼容未来配置键的扩展字段。 */
|
||||
/** 未知设置键只能承载服务端声明的标量值,敏感值不进入该 UI 模型。 */
|
||||
[key: string]: string | number | boolean | undefined;
|
||||
}
|
||||
|
||||
/** 由当前 feature adapter 归一后的 AIReplySettings UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AIReplySettings {
|
||||
/** 是否启用账号 AI 回复。 */
|
||||
ai_enabled: boolean;
|
||||
/** 最大折扣比例。 */
|
||||
max_discount_percent: number;
|
||||
/** 最大折扣金额。 */
|
||||
max_discount_amount?: number;
|
||||
/** 最大砍价轮次。 */
|
||||
max_bargain_rounds: number;
|
||||
/** 自定义提示词。 */
|
||||
custom_prompts: string;
|
||||
}
|
||||
|
||||
/** AI 模型发现接口的具名响应。 */
|
||||
/** 由当前 feature adapter 归一后的 AIModelsResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface AIModelsResponse {
|
||||
/** 远端可用模型名称。 */
|
||||
models: string[];
|
||||
}
|
||||
|
||||
/** 简单资源创建接口的数值主键响应。 */
|
||||
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface MutationIDResponse {
|
||||
/** 资源创建是否完成。 */
|
||||
success: boolean;
|
||||
/** 新资源数值主键。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** 简单变更接口的统一成功响应。 */
|
||||
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface OperationResponse {
|
||||
/** 操作是否完成。 */
|
||||
success: boolean;
|
||||
/** 可选的操作说明。 */
|
||||
message?: string;
|
||||
/** 操作完成后是否需要重新登录。 */
|
||||
requires_relogin?: boolean;
|
||||
}
|
||||
@@ -126,6 +126,14 @@ const Settings: React.FC = () => {
|
||||
/>
|
||||
<p className="text-xs text-gray-500">0 表示不自动清理续期日志</p>
|
||||
</div>
|
||||
|
||||
<label className="flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 cursor-pointer">
|
||||
<input type="checkbox" className="mt-1" checked={settings.outbound_http_public_only || false} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSettings({ ...settings, outbound_http_public_only: event.target.checked })} />
|
||||
<span>
|
||||
<span className="block text-sm font-bold text-amber-900">限制用户配置的 HTTP 出站请求只能访问公网</span>
|
||||
<span className="mt-1 block text-xs leading-5 text-amber-800">开启后会同时约束 API 发货、AI、HTTP 通知、远程图片和远程滑块服务;保存后立即生效,可能使内网服务不可用。</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect,test } from 'vitest';
|
||||
import type { SystemSettings } from '../../../shared/api-contract/settings';
|
||||
import type { SystemSettings } from './api';
|
||||
import { buildPersistableSettings,createCredentials,createCredentialsMessage,isCurrentSettingsRequest,validateCredentials } from './state';
|
||||
|
||||
// settingsFixture 是覆盖敏感字段过滤和系统配置保留字段的最小草稿。
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { get,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import type { BuildInfo } from './types';
|
||||
|
||||
/** 读取服务健康检查与构建标识;请求支持随壳层卸载取消。 */
|
||||
export const getHealth = async (options?: RequestControlOptions): Promise<BuildInfo> => get('/health', undefined, options);
|
||||
export const getHealth = async (options?: RequestControlOptions): Promise<BuildInfo> => runContractRequest(/* signal 控制健康检查请求的取消和超时。 */ signal => contractClient.GET('/health', { signal }), options);
|
||||
|
||||
export type { BuildInfo } from './types';
|
||||
@@ -4,4 +4,10 @@ export interface BuildInfo {
|
||||
version: string;
|
||||
// commit 是当前服务对应的提交标识。
|
||||
commit: string;
|
||||
/** status 表示服务总体健康状态。 */
|
||||
status?: string;
|
||||
/** database 表示数据库连接状态。 */
|
||||
database?: string;
|
||||
/** build_time 表示构建时间。 */
|
||||
build_time?: string;
|
||||
}
|
||||
Loaded 100 of 325 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user